簡體   English   中英

PHP未從AJAX接收序列化數據

[英]PHP not receiving serialized data from AJAX

目標:從表單中獲取用戶輸入的數據,通過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'];

您是否在Submit事件上使用表單?

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)的form方法。 這是因為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 ...繞過數據發布<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();

        } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM