PHP ile jQuery Ajax POST örneği

Bir formdan bir veritabanına veri göndermeye çalışıyorum. İşte kullandığım form:

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

Tipik yaklaşım formu göndermektir, ancak bu tarayıcının yeniden yönlendirilmesine neden olur. jQuery ve Ajax kullanarak, formun tüm verilerini yakalamak ve bir PHP betiğine göndermek mümkün müdür (bir örnek, form.php)?

Çözüm

Temel .ajax kullanımı aşağıdaki gibi görünecektir:

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

});

Not: jQuery 1.8'den beri .success(), .error() ve .complete() işlevleri .done(), .fail() ve .always() işlevleri lehine kullanımdan kaldırılmıştır.

Not: Yukarıdaki kod parçacığının DOM ready'den sonra yapılması gerektiğini unutmayın, bu nedenle bunu bir $(document).ready() işleyicisinin içine koymalısınız (veya $() kısaltmasını kullanın).

İpucu: Geri arama işleyicilerini şu şekilde zincirleyebilirsiniz: $.ajax().done().fail().always();

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

*Not: Enjeksiyonları ve diğer kötü amaçlı kodları önlemek için her zaman gönderilen verileri sterilize edin.

Yukarıdaki JavaScript kodunda .ajax yerine .post kısaltmasını da kullanabilirsiniz:

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

Not: Yukarıdaki JavaScript kodu jQuery 1.8 ve üstü ile çalışacak şekilde hazırlanmıştır, ancak jQuery 1.5.'e kadar önceki sürümlerle de çalışmalıdır.

Yorumlar (11)

jQuery* kullanarak bir Ajax isteği yapmak için bunu aşağıdaki kodla yapabilirsiniz.

HTML:


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



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

JavaScript:

Yöntem 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);
        }
    });

Yöntem 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');
    });

.success(),.error()ve.complete()geri aramaları *jQuery 1.8* itibariyle kullanımdan kaldırılmıştır. Kodunuzu bunların nihai olarak kaldırılmasına hazırlamak için, bunların yerine.done(),.fail()ve.always()` kullanın.

MDN: abort() . İstek zaten gönderilmişse, bu yöntem isteği iptal eder.

Böylece başarılı bir şekilde Ajax isteği gönderdik ve şimdi sıra sunucuya veri göndermeye geldi.

PHP

Bir Ajax çağrısında POST isteği yaptığımız için (type: "post"), artık $_REQUEST veya $_POST kullanarak veri alabiliriz:

  $bar = $_POST['bar']

POST isteğinde ne elde ettiğinizi basitçe şu şekilde de görebilirsiniz. Bu arada, $_POST ayarının yapıldığından emin olun. Aksi takdirde hata alırsınız.

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

Ve veritabanına bir değer ekliyorsunuz. Sorguyu yapmadan önce tüm istekleri (ister GET ister POST yapmış olun) düzgün bir şekilde duyarsızlaştırdığınızdan veya kaçırdığınızdan emin olun. En iyisi hazırlanmış ifadeler kullanmaktır.

Ve herhangi bir veriyi sayfaya geri döndürmek istiyorsanız, bunu aşağıdaki gibi bu veriyi yankılayarak yapabilirsiniz.

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

Ve sonra onu alabilirsin:

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

Birkaç kısaltılmış yöntem vardır. Aşağıdaki kodu kullanabilirsiniz. Aynı işi yapar.

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

serialize kullanabilirsiniz. Aşağıda bir örnek verilmiştir.

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