jQuery Ajax POST exemplo com PHP

Estou a tentar enviar dados de um formulário para uma base de dados. Aqui está o formulário que estou a usar:

<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>

A abordagem típica seria submeter o formulário, mas isso faz com que o navegador seja redirecionado. Usando jQuery e Ajax, é possível capturar todos os dados do formulário's e enviá-lo para um script PHP (um exemplo, form.php)?

Solução

O uso básico de .ajax seria algo parecido com isto:

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);
    });

});

Note: Desde jQuery 1.8, .success(), .error() e .complete() são depreciados em favor de .done(), .fail() e .always().

Note: Lembre-se que o trecho acima tem que ser feito após o DOM pronto, então você deve colocá-lo dentro de um $(document).ready() handler (ou utilizar o $() shorthand).

Tip: Você pode cadeia os manipuladores de chamadas como este: $.ajax().done().fail().always();

PHP (isto é, 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;

Note: Always sanitize dados postados, to prevent injections and other malicious code.

Você também poderia utilizar o estenógrafo .post no lugar de .ajax no código JavaScript acima:

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

Note: O código JavaScript acima é feito para funcionar com jQuery 1.8 e posteriores, mas deve funcionar com versões anteriores até jQuery 1.5.

Comentários (11)

Para fazer um pedido Ajax usando jQuery você pode fazer isso através do seguinte 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');
    });

Os .success(), .error(), e .complete() callbacks são depreciados a partir de jQuery 1.8. Para preparar seu código para sua eventual remoção, utilize .done(), .fail(), e .always() em seu lugar.

MDN: abortar()` . Se o pedido já tiver sido enviado, este método abortará o pedido.

Então, enviamos com sucesso um pedido Ajax, e agora é hora de pegar os dados para o servidor.

**PHP***

Como fazemos um pedido POST numa chamada Ajax (type: "post"), podemos agora obter dados utilizando $_REQUEST ou $_POST:

  $bar = $_POST['bar']

Você também pode ver o que você recebe no pedido do POST simplesmente por um ou outro. BTW, certifique-se de que $_POST está definido. Caso contrário, você receberá um erro.

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

E você está inserindo um valor na base de dados. Certifique-se de que você está sensibilizando ou escaping Todos os pedidos (se você fez um GET ou POST) corretamente antes de fazer a consulta. O melhor seria usar declarações preparadas.

E se você quiser retornar quaisquer dados de volta à página, você pode fazê-lo apenas ecoando esses dados como abaixo.

// 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'));

E depois podes conseguir como:

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

Há um par de métodos abreviados. Você pode usar o código abaixo. Ele faz o mesmo trabalho.

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

Você pode usar a seriedade. Abaixo está um exemplo.

$("#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;
    });
Comentários (1)