Ejemplo de jQuery Ajax POST con PHP

Estoy intentando enviar datos desde un formulario a una base de datos. Este es el formulario que estoy utilizando:

<form name="foo" action="form.php" method="POST" id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

El enfoque típico sería enviar el formulario, pero esto hace que el navegador se redirija. Usando jQuery y Ajax, ¿es posible capturar todos los datos del formulario y enviarlos a un script PHP (un ejemplo, form.php)?

Solución

El uso básico de .ajax sería algo así:

HTML:


    A bar
    <input id="bar" name="bar" type="text" value="" />

    <input type="submit" value="Send" />

jQuery:

// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

    // Prevent default posting of form - put here to work in case of errors
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

});

*Nota: Desde jQuery 1.8, .success(), .error() y .complete() están obsoletos en favor de .done(), .fail() y .always().

*Nota: Recuerde que el fragmento de arriba tiene que hacerse después del DOM ready, por lo que debe ponerlo dentro de un manejador $(document).ready() (o usar la abreviatura $()).

Consejo: Puedes encadenar los manejadores de devolución de llamada así: $.ajax().done().fail().always();

PHP (es decir, form.php):

// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;

Nota: Siempre sanear los datos publicados, para evitar inyecciones y otros códigos maliciosos.

También puede utilizar la abreviatura .post en lugar de .ajax en el código JavaScript anterior:

$.post('/form.php', serializedData, function(response) {
    // Log the response to the console
    console.log("Response: "+response);
});

Nota: El código JavaScript anterior está hecho para funcionar con jQuery 1.8 y posteriores, pero debería funcionar con versiones anteriores hasta jQuery 1.5..

Comentarios (11)

Para hacer una petición Ajax usando jQuery puedes hacerlo con el siguiente código.

HTML:


    A bar
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />



<div id="result"></div>

JavaScript:

**Método 1

 /* Get from elements values */
 var values = $(this).serialize();

 $.ajax({
        url: "test.php",
        type: "post",
        data: values ,
        success: function (response) {

           // You will get response from your PHP page (what you echo or print)
        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }
    });

**Método 2

/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
    var ajaxRequest;

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get from elements values */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div. */
    /* I am not aborting the previous request, because it's an
       asynchronous request, meaning once it's sent it's out
       there. But in case you want to abort it you can do it
       by abort(). jQuery Ajax methods return an XMLHttpRequest
       object, so you can just use abort(). */
       ajaxRequest= $.ajax({
            url: "test.php",
            type: "post",
            data: values
        });

    /*  Request can be aborted by ajaxRequest.abort() */

    ajaxRequest.done(function (response, textStatus, jqXHR){

         // Show successfully for submit message
         $("#result").html('Submitted successfully');
    });

    /* On failure of request this function will be called  */
    ajaxRequest.fail(function (){

        // Show error
        $("#result").html('There is error while submit');
    });

Los callbacks .success(), .error() y .complete() están obsoletos a partir de jQuery 1.8. Para preparar su código para su eventual eliminación, utilice .done(), .fail() y .always() en su lugar.

MDN: abort() . Si la petición ya ha sido enviada, este método abortará la petición.

Así que hemos enviado con éxito una petición Ajax, y ahora es el momento de agarrar los datos al servidor.

PHP

Como hacemos una petición POST en una llamada Ajax (type: "post"), ahora podemos agarrar los datos usando ya sea$_REQUESTo$_POST`:

  $bar = $_POST['bar']

También puedes ver lo que obtienes en la petición POST simplemente con cualquiera de los dos. Por cierto, asegúrese de que $_POST está configurado. De lo contrario, obtendrá un error.

var_dump($_POST);
// Or
print_r($_POST);

Y usted está insertando un valor en la base de datos. Asegúrate de que estás sensibilizando o escapando todas las peticiones (tanto si has hecho un GET como un POST) correctamente antes de hacer la consulta. Lo mejor sería usar prepared statements.

Y si quieres devolver algún dato a la página, puedes hacerlo simplemente haciendo eco de esos datos como abajo.

// 1. Without JSON
   echo "Hello, this is one"

// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));

Y entonces usted puede obtener como:

 ajaxRequest.done(function (response){
    alert(response);
 });

Hay un par de métodos abreviados. Puedes usar el código de abajo. Hace el mismo trabajo.

var ajaxRequest= $.post("test.php", values, function(data) {
  alert(data);
})
  .fail(function() {
    alert("error");
  })
  .always(function() {
    alert("finished");
});
Comentarios (8)

Puedes utilizar serializar. A continuación se muestra un ejemplo.

$("#submit_btn").click(function(){
    $('.error_status').html();
        if($("form#frm_message_board").valid())
        {
            $.ajax({
                type: "POST",
                url: "<?php echo site_url('message_board/add');?>",
                data: $('#frm_message_board').serialize(),
                success: function(msg) {
                    var msg = $.parseJSON(msg);
                    if(msg.success=='yes')
                    {
                        return true;
                    }
                    else
                    {
                        alert('Server error');
                        return false;
                    }
                }
            });
        }
        return false;
    });
Comentarios (1)