PHP 没有收到来自 AJAX 的序列化数据

PHP not receiving serialized data from AJAX

目标:从表单中获取用户输入的数据,运行 通过 jquery 验证,然后 post 变量到 php 脚本,用于将数据存储到数据库中。

问题:Ajax 请求脚本正在运行并生成序列化数据;然而,PHP 脚本 returns 一个空的 POST 数组。

JS 控制台日志:生成序列化数据字符串并包含以下形式的变量:x_first_name 和 x_last_name.

PHP 中的错误:所有 POST 变量的未定义索引。

HTML:

<form method="post" action="processsale.php" id="checkout_form" name="checkout_form">
  <fieldset>

    <div class="form-group">
      <label for="x_first_name" class="control-label">First Name</label>
        <input name="x_first_name" id="x_first_name" type="text" class="input-lg form-control cc-owner" autocomplete="x_first_name" placeholder="First Name" required/>
    </div>

    <div class="form-group">
        <label for="x_last_name" class="control-label">Last Name</label>
          <input name="x_last_name" id="x_last_name" type="text" class="input-lg form-control" autocomplete="x_last_name" placeholder="Last Name" required/>
    </div>

  </fieldset>
</form>

AJAX 片段:

    <script>
  $(document).ready(function() {

   // Variable to hold request
      var request;


        $('#checkout_form').submit(function(e) {

        e.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();

        // Disabled form elements will not be serialized.
        $inputs.prop("disabled", true);

        // Fire off the request to processsale.php
        request = $.ajax({
            url: "processsale.php",
            type: "POST",
            data: serializedData
        });


        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it worked!");
            console.log(serializedData)
            window.location.replace("processsale.php")
        });
        return false;

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

        }); // end of form submit

    });

  }); //End of doc ready
  </script>

PHP (processsale.php) 片段:

print_r($_POST);
echo $_POST['x_first_name'];
echo $_POST['x_last_name'];

试试这个,但我只是创建 post 按钮,当您在填写表格后单击该按钮时,您可以在 php 文件中获取输入的值

function formsubmit(){
           //but when perform an event that time only you will get the post data

        // setup some local variables
       //In this use your form id here
        var $form = $('#checkout_form');

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

        request = $.ajax({
            url: "processsale.php",
            type: "POST",
            data:  serializedData,
            success: function(data){
                 console.log(data);
               }
        });

        request.done(function (response, textStatus, jqXHR){
            // Log a message to the console
            console.log("Hooray, it worked!");
            console.log(serializedData)
            window.location.replace("processsale.php")
        });
 }      

html 文件

        <form method="post" action="processsale.php" id="checkout_form" name="checkout_form">
          <fieldset>

            <div class="form-group">
              <label for="x_first_name" class="control-label">First Name</label>
                <input name="x_first_name" id="x_first_name" type="text" class="input-lg form-control cc-owner" autocomplete="x_first_name" placeholder="First Name" required/>
            </div>

            <div class="form-group">
                <label for="x_last_name" class="control-label">Last Name</label>
                  <input name="x_last_name" id="x_last_name" type="text" class="input-lg form-control" autocomplete="x_last_name" placeholder="Last Name" required/>
            </div>

          </fieldset>
        </form>
    <input type='button' value='post' onClick="formsubmit()"/>

获取 processsale.php 文件中的 post 值

<?php 

 //get post value from ajax
 if(isset($_POST)){

   print_r($_POST);
   echo $_POST['x_first_name'];
   echo $_POST['x_last_name'];

  }

?>

您是否在提交事件中使用表单?

Javascript $(文档).ready(函数(){ $("#checkout_form").submit(函数(){ 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();

    console.log(serializedData)

    request = $.ajax({
        url: "test.php",
        type: "POST",
        data: serializedData
    });

    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
        console.log(serializedData)
        //window.location.replace("processsale.php")
    });
    return false;
    });
    });

HTML

<form method="post" action="processsale.php" id="checkout_form" name="checkout_form">
  <fieldset>

    <div class="form-group">
      <label for="x_first_name" class="control-label">First Name</label>
        <input name="x_first_name" id="x_first_name" type="text" class="input-lg form-control cc-owner" autocomplete="x_first_name" placeholder="First Name" required/>
    </div>

    <div class="form-group">
        <label for="x_last_name" class="control-label">Last Name</label>
          <input name="x_last_name" id="x_last_name" type="text" class="input-lg form-control" autocomplete="x_last_name" placeholder="Last Name" required/>
    </div>

  </fieldset>
  <button type="submit" id="harchivemenus">Submit</button>

</form>

我想通了!我的错误:我试图 post 数据两次。

通过我的 HTML 表单元素:

<form method="post" action="processsale.php" id="checkout_form" name="checkout_form">

以及通过 ajax:

       e.preventDefault();

...

 request = $.ajax({
        url: "processsale.php",
        type: "POST",
        data:  serializedData,
        success: function(data){
             console.log(data);
           }
    });

request.done(function (response, textStatus, jqXHR){
    // Log a message to the console
    console.log("Hooray, it worked!");
    console.log(serializedData);
    //redirect to php script to process form data
    window.location.replace("processsale.php")
});

我的 js 忽略了我的表单方法 post 到 php (processsale.php)。这是因为 e.preventDefault(); 阻止了提交表单的默认方式(通过 HTML 元素 <form method="post"...。但是,它通过 ajax 成功地 posting 了表单数据,正如我的 console.log(serializedData) 所验证的那样。虽然数据是通过 ajax posted 到我的 php 脚本的,但当我重定向到我的 php 脚本通过 window.location.replace("processsale.php")。那是因为 window.location.replace 运行 php 脚本,就像新访问过一样,没有来自 [=54] 的任何 posted 数据=].

解决方案

我 运行 通过 jquery 验证表单,如果验证成功,我将使用 HTML <form method="post" action="processsale.php"> 提交表单。这样我就避免了使用 window.location.replace("processsale.php") 因为这只是打开脚本而不抓取任何 posted 表单数据。

然而,如果表单无法通过 jquery 验证,并且验证失败,我使用 e.preventDefault(); 绕过 post 通过 HTML 元素 <form ... 这可以防止 post 向我的 php 脚本输入无效的表单数据。

这是我添加到代码中的内容。仅供参考:text-success 是成功验证的输出。

        //if jquery validation is successful
        if ($('.text-success').length){ 

                //send msg in console
                console.log("SUCCESS!");
                return true;

        //if jquery validation fails
        } else {

            console.log("Errors on page");

            //prevent from submitting form normally: via html form element
            e.preventDefault();

        }