PHP未从AJAX接收序列化数据

PHP not receiving serialized data from AJAX

本文关键字:序列化 数据 未从 AJAX PHP      更新时间:2023-09-26

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

问题:Ajax请求脚本正在工作并生成序列化的数据;但是,PHP脚本返回一个空的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'];

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

Javascript$(document).ready(function){$("#checkout_form").submit(function(){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>

试试这个,但我只是创建了发布按钮,当你在填写表单后点击该按钮时,你可以在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文件中获取后值

<?php 
 //get post value from ajax
 if(isset($_POST)){
   print_r($_POST);
   echo $_POST['x_first_name'];
   echo $_POST['x_last_name'];
  }
?>

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

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

解决方案

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

但是,如果表单无法通过jquery进行验证,并且验证失败,我使用e.preventDefault();绕过通过HTML元素<form ...发布数据。这可以防止将无效的表单数据发布到我的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();
        }