带有 PHP 的 jQuery Ajax POST 示例

IT技术 javascript jquery ajax post
2020-12-10 23:12:33

我正在尝试将数据从表单发送到数据库。这是我正在使用的表格:

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

典型的方法是提交表单,但这会导致浏览器重定向。使用 jQuery 和Ajax是否可以捕获所有表单数据并将其提交给 PHP 脚本(例如form.php)?

6个回答

的基本用法.ajax如下所示:

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

});

注意:自 jQuery 1.8 起,.success(),.error().complete()被弃用,而支持.done(),.fail().always()

注意:请记住,上面的代码片段必须在 DOM 准备好后完成,因此您应该将它放在$(document).ready()处理程序中(或使用$()速记)。

提示:您可以像这样链接回调处理程序:$.ajax().done().fail().always();

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

注意:始终清理发布的数据,以防止注入和其他恶意代码。

您还可以使用简写.post代替.ajax上面的 JavaScript 代码:

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

注意:上述 JavaScript 代码适用于 jQuery 1.8 及更高版本,但它应该适用于 jQuery 1.5 之前的版本。

@PhilibertPerusse 与任何事件绑定一样,您显然需要在尝试绑定到 DOM 之前该元素存在于 DOM 中,或者如果您使用委托绑定。
2021-02-19 23:12:33
如果您将此应用于您自己的代码,请注意“名称”属性对输入至关重要,否则serialize()将跳过它们。
2021-02-25 23:12:33
是的,我现在明白了。但是我发现很多示例总是放置一个 $(document).ready 块,以便该示例是自包含的。我为未来的用户写了评论,他可能会像我一样偶然发现这个问题并最终阅读评论线程和这个初学者“提示”
2021-02-26 23:12:33
一个非常重要的说明,因为我花了/浪费/投入了很多时间来尝试使用这个例子。您需要在 $(document).ready 块内绑定事件,或者在执行绑定之前加载 FORM。否则,您会花费大量时间试图弄清楚为什么不调用绑定。
2021-03-02 23:12:33

要使用jQuery发出 Ajax 请求,您可以通过以下代码执行此操作。

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:

方法一

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

方法二

/* 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().complete()回调不赞成使用的jQuery 1.8要准备的代码为他们的最终消除,使用.done().fail().always()来代替。

MDN: abort(). 如果请求已经发送,此方法将中止请求。

所以我们已经成功发送了一个 Ajax 请求,现在是时候向服务器抓取数据了。

PHP

当我们在 Ajax 调用 ( type: "post")中发出 POST 请求时,我们现在可以使用$_REQUEST获取数据$_POST

  $bar = $_POST['bar']

您还可以通过简单地查看您在 POST 请求中获得的内容。顺便说一句,请确保$_POST已设置。否则你会得到一个错误。

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

您正在向数据库中插入一个值。在进行查询之前,请确保您正确地敏感转义所有请求(无论是 GET 还是 POST)。最好的方法是使用准备好的语句

如果你想将任何数据返回到页面,你可以通过像下面这样回显数据来实现。

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

然后你可以得到它:

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

有几种速记方法您可以使用以下代码。它做同样的工作。

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

我想分享如何使用 PHP + Ajax 发布以及失败时返回的错误的详细方法。

首先,创建两个文件,例如form.phpprocess.php

我们将首先创建一个form,然后使用该jQuery .ajax()方法提交其余的将在评论中解释。


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>


使用 jQuery 客户端验证来验证表单并将数据传递给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
    });
});

现在我们来看看 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);

项目文件可以从http://projects.decodingweb.com/simple_ajax_form.zip下载

您可以使用序列化。下面是一个例子。

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

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