jQuery Ajax POST przykład z PHP

Próbuję wysłać dane z formularza do bazy danych. Oto formularz, którego używam:

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

Typowym podejściem byłoby przesłanie formularza, ale powoduje to przekierowanie przeglądarki. Używając jQuery i Ajax , można przechwycić wszystkie dane formularza i przesłać je do skryptu PHP (na przykład formularz .php )?

Author: Taryn, 2011-02-15

11 answers

Podstawowe użycie .ajax wyglądałoby to mniej więcej tak:

HTML:

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />

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

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

});

Uwaga: Od jQuery 1.8, .success(), .error() i .complete() są przestarzałe na rzecz .done(), .fail() i .always().

Uwaga: Pamiętaj, że powyższy fragment musi być wykonany po DOM ready, więc powinieneś umieścić go w środku $(document).ready() handler (lub użyj skrótu $()).

Wskazówka: Możesz łańcuch obsługa wywołania zwrotnego jak to: $.ajax().done().fail().always();

PHP (czyli 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;

Uwaga: zawsze dezynfekuj opublikowane dane , aby zapobiec zastrzykom i innym złośliwym kodom.

Możesz również użyć skrótu .post w miejsce .ajax w powyższym kodzie JavaScript:

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

Uwaga: powyższy kod JavaScript jest stworzony do pracy z jQuery 1.8 i nowszymi wersjami, ale powinien działać z poprzednimi wersjami do jQuery 1.5.

 855
Author: Marcus Ekwall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-04 08:29:50

Aby wykonać żądanie ajax używając jQuery możesz to zrobić za pomocą kodu

HTML:

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>

JavaScript:

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


    });

Metoda 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 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 cab be abort 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');
     });

The .success(), .error(), i .complete() wywołania zwrotne są przestarzałe od jQuery 1.8. Aby przygotować kod do ich ewentualnego usunięcia, użyj .done(), .fail(), i .always() zamiast tego.

MDN: abort() . Jeżeli wniosek został wysłany już ta metoda przerywa żądanie.

Więc udało nam się wysłać żądanie ajax teraz jego czas, aby pobrać dane do serwera.

PHP

W ten sposób możemy uzyskać dostęp do danych za pomocą funkcji ajax ( $_REQUEST lub $_POST
  $bar = $_POST['bar']

Możesz również zobaczyć, co dostajesz w żądaniu POST, po prostu albo, Btw upewnij się, że $_POST jest ustawiony inaczej dostaniesz błąd.

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

I wstawiasz wartość do bazy danych upewnij się jesteś uczulający lub uciekając {[20] } wszystkie żądania ( pogodę, którą zrobiłeś GET lub POST) prawidłowo przed dokonaniem zapytania, najlepiej byłoby użyć przygotowane Oświadczenia.

I jeśli chcesz zwrócić jakiekolwiek dane z powrotem na stronę, możesz to zrobić, po prostu powtarzając te dane, jak poniżej.

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

And than you can get it like

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

Istnieje kilka metod stenograficznych możesz użyć poniższego kodu, aby wykonać tę samą pracę.

var ajaxRequest= $.post( "test.php",values, function(data) {
  alert( data );
})
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});
 183
Author: NullPoiиteя,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-22 05:35:42

Chciałbym podzielić się szczegółowym sposobem, jak pisać z PHP + Ajax wraz z błędami wyrzuconymi z powrotem na niepowodzenie.

Najpierw utwórz dwa pliki, na przykład form.php i process.php.

Najpierw utworzymy form, który następnie zostanie przesłany za pomocą jQuery .ajax() metoda. Reszta zostanie wyjaśniona w komentarzach.


form.php

<form method="post" name="postForm">
    <ul>
        <li>
            <label>Name</label>
            <input type="text" name="name" id="name" placeholder="Bruce Wayne">
            <span class="throw_error"></span>
            <span id="success"></span>
       </li>
   </ul>
   <input type="submit" value="Send" />
</form>


Zatwierdź formularz za pomocą walidacji po stronie klienta jQuery i przekaż dane do process.php.

$(document).ready(function() {
    $('form').submit(function(event) { //Trigger on form submit
        $('#name + .throw_error').empty(); //Clear the messages first
        $('#success').empty();

        //Validate fields if required using jQuery

        var postForm = { //Fetch form data
            'name'     : $('input[name=name]').val() //Store name fields value
        };

        $.ajax({ //Process the form using $.ajax()
            type      : 'POST', //Method type
            url       : 'process.php', //Your form processing file URL
            data      : postForm, //Forms name
            dataType  : 'json',
            success   : function(data) {
                            if (!data.success) { //If fails
                                if (data.errors.name) { //Returned if any error from process.php
                                    $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
                                }
                            }
                            else {
                                    $('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
                                }
                            }
        });
        event.preventDefault(); //Prevent the default submit
    });
});

Teraz przyjrzymy się process.php

$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`

/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
    $errors['name'] = 'Name cannot be blank';
}

if (!empty($errors)) { //If errors in validation
    $form_data['success'] = false;
    $form_data['errors']  = $errors;
}
else { //If not, process the form, and return true on success
    $form_data['success'] = true;
    $form_data['posted'] = 'Data Was Posted Successfully';
}

//Return the data back to form.php
echo json_encode($form_data);

Pliki projektu można pobrać z http://projects.decodingweb.com/simple_ajax_form.zip .

 44
Author: Mr. Alien,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-01 07:04:48

Możesz użyć serialize. Poniżej znajduje się przykład.

$("#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;
    });
 25
Author: Peter Mortensen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-19 21:53:50

HTML :

    <form name="foo" action="form.php" method="POST" id="foo">
        <label for="bar">A bar</label>
        <input id="bar" class="inputs" name="bar" type="text" value="" />
        <input type="submit" value="Send" onclick="submitform(); return false;" />
    </form>

JavaScript :

   function submitform()
   {
       var inputs = document.getElementsByClassName("inputs");
       var formdata = new FormData();
       for(var i=0; i<inputs.length; i++)
       {
           formdata.append(inputs[i].name, inputs[i].value);
       }
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
           xmlhttp = new XMLHttpRequest;
       }
       else
       {
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange = function()
       {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
          {

          }
       }
       xmlhttp.open("POST", "insert.php");
       xmlhttp.send(formdata);
   }
 19
Author: DDeme,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-05 13:55:09

Używam tego way.It wyślij wszystko jak Pliki

$(document).on("submit", "form", function(event)
{
    event.preventDefault();

    var url=$(this).attr("action");
    $.ajax({
        url: url,
        type: 'POST',
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {
            console.log("error");

        }
    });        

});
 13
Author: Shaiful Islam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-03 21:41:14
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
    <button id="desc" name="desc" value="desc" style="display:none;">desc</button>
    <button id="asc" name="asc"  value="asc">asc</button>
    <input type='hidden' id='check' value=''/>
</form>

<div id="demoajax"></div>

<script>
    numbers = '';
    $('#form_content button').click(function(){
        $('#form_content button').toggle();
        numbers = this.id;
        function_two(numbers);
    });

    function function_two(numbers){
        if (numbers === '')
        {
            $('#check').val("asc");
        }
        else
        {
            $('#check').val(numbers);
        }
        //alert(sort_var);

        $.ajax({
            url: 'test.php',
            type: 'POST',
            data: $('#form_content').serialize(),
            success: function(data){
                $('#demoajax').show();
                $('#demoajax').html(data);
                }
        });

        return false;
    }
    $(document).ready(function_two());
</script>
 8
Author: john,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-22 11:38:39

Jeśli chcesz wysyłać dane za pomocą jquery Ajax, nie ma potrzeby tagowania formularza i przycisku submit

Przykład:

<script>
    $(document).ready(function () {
        $("#btnSend").click(function () {
            $.ajax({
                url: 'process.php',
                type: 'POST',
                data: {bar: $("#bar").val()},
                success: function (result) {
                    alert('success');
                }
            });
        });
    });
</script>
<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />
 6
Author: Juned Ansari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-13 13:08:28

Obsługa błędu ajax i loader przed przesłaniem i po przesłaniu sukcesu Pokaż okno startowe alertu z przykładem:

var formData = formData;

$.ajax({
    type: "POST",
    url: url,
    async: false,
    data: formData, //only input
    processData: false,
    contentType: false,
    xhr: function ()
    {
        $("#load_consulting").show();
        var xhr = new window.XMLHttpRequest();
        //Upload progress
        xhr.upload.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = (evt.loaded / evt.total) * 100;
                $('#addLoad .progress-bar').css('width', percentComplete + '%');
            }
        }, false);
        //Download progress
        xhr.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
            }
        }, false);
        return xhr;
    },
    beforeSend: function (xhr) {
        qyuraLoader.startLoader();
    },
    success: function (response, textStatus, jqXHR) {
        qyuraLoader.stopLoader();
        try {
            $("#load_consulting").hide();

            var data = $.parseJSON(response);
            if (data.status == 0)
            {
                if (data.isAlive)
                {
                    $('#addLoad .progress-bar').css('width', '00%');
                    console.log(data.errors);
                    $.each(data.errors, function (index, value) {
                        if (typeof data.custom == 'undefined') {
                            $('#err_' + index).html(value);
                        }
                        else
                        {
                            $('#err_' + index).addClass('error');

                            if (index == 'TopError')
                            {
                                $('#er_' + index).html(value);
                            }
                            else {
                                $('#er_TopError').append('<p>' + value + '</p>');
                            }
                        }

                    });
                    if (data.errors.TopError) {
                        $('#er_TopError').show();
                        $('#er_TopError').html(data.errors.TopError);
                        setTimeout(function () {
                            $('#er_TopError').hide(5000);
                            $('#er_TopError').html('');
                        }, 5000);
                    }
                }
                else
                {
                    $('#headLogin').html(data.loginMod);
                }
            } else {
                //document.getElementById("setData").reset();
                $('#myModal').modal('hide');
                $('#successTop').show();
                $('#successTop').html(data.msg);
                if (data.msg != '' && data.msg != "undefined") {

                    bootbox.alert({closeButton: false, message: data.msg, callback: function () {
                            if (data.url) {
                                window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                            } else {
                                location.reload(true);
                            }
                        }});
                } else {

                    bootbox.alert({closeButton: false, message: "Success", callback: function () {
                            if (data.url) {
                                window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                            } else {
                                location.reload(true);
                            }
                        }});
                }

            }
        } catch (e) {
            if (e) {
                $('#er_TopError').show();
                $('#er_TopError').html(e);
                setTimeout(function () {
                    $('#er_TopError').hide(5000);
                    $('#er_TopError').html('');
                }, 5000);
            }
        }
    }
});
 3
Author: pawan sen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-20 13:19:53

Używam tego prostego kodu od lat bez problemu. (Wymaga jquery)

<script type="text/javascript">
function ap(x,y) {$("#" + y).load(x);};
function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>

Tutaj ap () oznacza stronę ajax, a Af () oznacza formę ajax. W formularzu po prostu wywołanie funkcji AF () spowoduje wysłanie formularza do adresu url i załadowanie odpowiedzi na żądany element html.

<form>
...
<input type="button" onclick="af('http://example.com','load_response')"/>
</form>
<div id="load_response">this is where response will be loaded</div>
 2
Author: Uchiha Itachi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-08 14:22:41

Witam proszę sprawdzić to jest kompletny kod żądania ajax.

        $('#foo').submit(function(event) {
        // get the form data
        // there are many ways to get this data using jQuery (you can use the 
    class or id also)
    var formData = $('#foo').serialize();
    var url ='url of the request';
    // process the form.

    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use
        url         : 'url/', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json', // what type of data do we expect back.
        beforeSend : function() {
        //this will run before sending an ajax request do what ever activity 
         you want like show loaded 
         },
        success:function(response){
            var obj = eval(response);
            if(obj)
            {  
                if(obj.error==0){
                alert('success');
                }
            else{  
                alert('error');
                }   
            }
        },
        complete : function() {
           //this will run after sending an ajax complete                   
                    },
        error:function (xhr, ajaxOptions, thrownError){ 
          alert('error occured');
        // if any error occurs in request 
        } 
    });
    // stop the form from submitting the normal way and refreshing the page
    event.preventDefault();
});
 0
Author: Waseem Bashir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-23 06:58:54