簡體   English   中英

jQuery AJAX響應始終返回空白消息

[英]jQuery AJAX response always returns blank message

嗨,我正在嘗試制作HTML表單,並且需要在執行表單操作之前對其進行驗證。 但是AJAX響應總是返回空消息嗎?

$(function(){
    $("#ajax-payment-form input[type='submit']").click(function(e) {

        // Prevent form submission
        e.preventDefault();

        // Serialize data, make AJAX call
        var str = $(this).serialize();
        $.ajax({
            type: "POST",
            url: templateDir+"/payment_form/payment_process.php",
            data: str,
            context: this
        }).done(function(msg) {

            if(msg == 'OK') {
                 console.log('Validation passed, will submit form');
                 $(this).closest('form').submit();
            } else {
                 console.log(msg);
            }

        }).fail(function() {
            // Catch ajax errors here
            console.log('AJAX error');
        });
    });                                                         
});

PHP:

$post = (!empty($_POST)) ? true : false;
if ($post) {
  $orderid = stripslashes($_POST['orderid']);
  $amount = stripslashes($_POST['amount']);
  $betingelser = stripslashes($_POST['betingelser']);
  $error = ''; // Check ordreid
  if (!$orderid) {
    $error. = 'Venligst indtast dit ordreid.<br />';
  } // Check amount
  if (!$amount) {
    $error. = 'Venligst indtast et beløb.<br />';
  }
  if (!$error) {
    echo 'OK';
  } else {
    echo '<div class="notification_error">'.$error.
    '</div>';
  }
}

誰能告訴我怎么了?

您位於submit按鈕的click處理程序中。 您正在調用$(this).serialize()this是該提交按鈕。 在提交按鈕上調用序列化將返回一個空字符串。

因此,您沒有將任何數據傳遞到服務器。 在服務器端執行的第一件事是檢查empty($_POST)它將為 ,因此, if ($post)為false,則不會執行任何服務器端代碼。

您需要序列化表單 ,而不是提交按鈕。

一個簡單的解決方案是序列化表單本身。

str = $('"#ajax-payment-form').serialize()

但實際上,更大的問題是您綁定了click提交按鈕,而不是綁定到表單本身上的submit事件。

而不是這種復雜的表單提交方式...

$("#ajax-payment-form input[type='submit']").click(function(e) {

只要這樣做:

$("#ajax-payment-form").submit(function (e) {

試試這個在jQuery中:

$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this,
success: function(msg){
if(msg == 'OK') {
    console.log('Validation passed, will submit form');
    $(this).closest('form').submit();
    } 
else {
    console.log(msg);
}
}
error: function(msg){
// if call fails or any error occurs
}
});

暫無
暫無

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

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