Send POST to PHP through AJAX

7

I need that when I click on a button through POST I send a data to a PHP file where I make a query with that parameter that I receive to generate a graph. I have done it by means of a form, but an inconvenience arises when clicking on that button: a modal must be opened with the graph inside. Therefore, the page can not be reloaded.

I have read that it can be done with AJAX, but I have never used it and I do not understand it much. I do not know what other ways a POST can do without having to reload the page.

My project uses jQuery.

    
asked by Lina Cortés 21.09.2016 в 20:55
source

2 answers

9

Using jquery is relatively easy to use ajax, then I'll give you a simple example:

This would be your HTML file where you make the ajax call

<html>
<head>
<title>Ejemplo sencillo de AJAX</title>
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function realizaProceso(valorCaja1, valorCaja2){
        var parametros = {
                "valorCaja1" : valorCaja1,
                "valorCaja2" : valorCaja2
        };
        $.ajax({
                data:  parametros, //datos que se envian a traves de ajax
                url:   'ejemplo_ajax_proceso.php', //archivo que recibe la peticion
                type:  'post', //método de envio
                beforeSend: function () {
                        $("#resultado").html("Procesando, espere por favor...");
                },
                success:  function (response) { //una vez que el archivo recibe el request lo procesa y lo devuelve
                        $("#resultado").html(response);
                }
        });
}
</script>
</head>
<body>
Introduce valor 1
<input type="text" name="caja_texto" id="valor1" value="0"/> 
Introduce valor 2
<input type="text" name="caja_texto" id="valor2" value="0"/>
Realiza suma
<input type="button" href="javascript:;" onclick="realizaProceso($('#valor1').val(), $('#valor2').val());return false;" value="Calcula"/>
<br/>
Resultado: <span id="resultado">0</span>
</body>
</html>

In addition to this file you must have a file that processes the ajax request, this case is called example_ajax_process.php , this file will contain the following:

<?php 
$resultado = $_POST['valorCaja1'] + $_POST['valorCaja2']; 
echo $resultado; //haciendo este echo estas respondiendo la solicitud ajax
?>

Try testing that code, so you'll have an idea of how ajax works.

    
answered by 21.09.2016 в 21:30
6

Some time ago I wrote a post on a blog about this, if you want to try it, it's more or less like this:

This would be your html :

<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="UTF-8" />
    <title> Acción onclick en js </title>
    // Aquí esta la referencia a jquery
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
  </head>
  <body>
    <form method="post" id="formulario">
        <input type="text" name="usuario" placeholder="Usuario" autofocus/>
        <input type="password" name="contrasena" placeholder="Contraseña"/>
        <input type="button" id="btn-ingresar" value="Ingresar" />
    </form>
    // Este div nos servirá para cachar la respuesta enviada 
    // por el backend en caso de que sea necesario.
    <div id="resp"></div>
  </body>
</html>

and here is the action of the button that will send the data of your form to your file php :

$(document).on('ready',function(){       
    $('#btn-ingresar').click(function(){
        var url = "datos_login.php";
        $.ajax({                        
           type: "POST",                 
           url: url,                     
           data: $("#formulario").serialize(), 
           success: function(data)             
           {
             $('#resp').html(data);               
           }
       });
    });
});

This is a part of what your file php would be called in this example as datos_login.php :

<?php   
    $usuario = $_POST['usuario'];
    $contra  = $_POST['contrasena'];

    echo "tu usuario es: ".$usuario; 
    echo "contraseña es: ".$contrsena;
?>

check it out and if you have any doubts you can check the reference of the post that I wrote here .

The complete code would look something like this:

<!DOCTYPE html>
<html lang="es">
  <head>
    <meta charset="UTF-8" />
    <title> Acción onclick en js </title>
    // Aquí esta la referencia a jquery
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script>
    $(document).on('ready',function(){

      $('#btn-ingresar').click(function(){
        var url = "datos_login.php";                                      

        $.ajax({                        
           type: "POST",                 
           url: url,                    
           data: $("#formulario").serialize(),
           success: function(data)            
           {
             $('#resp').html(data);           
           }
         });
      });
    });
    </script>
  </head>
  <body>
    <form method="post" id="formulario">
        <input type="text" name="usuario" placeholder="Usuario" autofocus/>
        <input type="password" name="contrasena" placeholder="Contraseña"/>
        <input type="button" id="btn-ingresar" value="Ingresar" />
    </form>
    // Este div nos servirá para cachar la respuesta enviada 
    // por el backend en caso de que sea necesario.
    <div id="resp"></div>
  </body>
</html>

Greetings.

    
answered by 21.09.2016 в 22:18