PHP没有从AJAX接收序列化数据

时间:2015-03-26 23:09:24

标签: javascript php jquery ajax post

目标:从表单中获取用户输入的数据,通过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'];

3 个答案:

答案 0 :(得分:1)

你在提交活动中使用表格吗?

的Javascript     $(文件)。就绪(函数(){         $(&#34;#checkout_form&#34)。提交(函数(){             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>

答案 1 :(得分:0)

尝试这个,但我只是在填写表单后单击该按钮创建帖子按钮,您可以在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'];

  }

?>

答案 2 :(得分:0)

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

通过我的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"...。但是,它已成功通过ajax发布表单数据,由我的console.log(serializedData)验证。虽然数据通过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();

        }