Esempio di jQuery Ajax POST con PHP

Sto cercando di inviare dati da un modulo a un database. Ecco il modulo che sto usando:

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

L'approccio tipico sarebbe quello di inviare il modulo, ma questo causa il reindirizzamento del browser. Usando jQuery e Ajax, è possibile catturare tutti i dati del modulo e inviarli a uno script PHP (un esempio, form.php)?

Soluzione

L'uso di base di .ajax sarebbe qualcosa del genere:

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: Da jQuery 1.8, .success(), .error() e .complete() sono deprecati in favore di .done(), .fail() e .always().

Nota: ricordate che lo snippet di cui sopra deve essere eseguito dopo il DOM ready, quindi dovreste metterlo all'interno di un gestore $(document).ready() (o usare l'abbreviazione $()).

Suggerimento: puoi concatenare i gestori di callback in questo modo: $.ajax().done().fail().always();

PHP (cioè 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: sempre sanitizzare i dati inviati, per prevenire iniezioni e altro codice maligno.

Si potrebbe anche usare l'abbreviazione .post al posto di .ajax nel codice JavaScript di cui sopra:

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

Nota: Il codice JavaScript qui sopra è fatto per funzionare con jQuery 1.8 e successive, ma dovrebbe funzionare con le versioni precedenti fino a jQuery 1.5.

Commentari (11)

Per fare una richiesta Ajax usando jQuery potete farlo con il seguente codice.

HTML:


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



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

JavaScript:

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

**Metodo 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');
    });

Le callback .success(), .error(), e .complete() sono deprecate a partire da jQuery 1.8. Per preparare il tuo codice alla loro eventuale rimozione, usa invece .done(), .fail(), e .always().

MDN: abort() . Se la richiesta è già stata inviata, questo metodo interrompe la richiesta.

Quindi abbiamo inviato con successo una richiesta Ajax, e ora è il momento di prendere i dati al server.

PHP

Dato che facciamo una richiesta POST in una chiamata Ajax (tipo: "post"), ora possiamo prendere i dati usando $_REQUEST o $_POST:

  $bar = $_POST['bar']

Si può anche vedere cosa si ottiene nella richiesta POST semplicemente con uno dei due. BTW, assicurati che $_POST sia impostato. Altrimenti otterrai un errore.

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

E stai inserendo un valore nel database. Assicurati di sensibilizzare o escludere tutte le richieste (sia che tu abbia fatto un GET o un POST) correttamente prima di fare la query. Il meglio sarebbe usare prepared statements.

E se volete restituire dei dati alla pagina, potete farlo semplicemente facendo l'eco di quei dati come qui sotto.

// 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 poi si può ottenere come:

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

Ci sono un paio di metodi stenografici. Puoi usare il codice qui sotto. Fa lo stesso lavoro.

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

Potete usare serialize. Qui sotto c'è un esempio.

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