2017-10-15 76 views
2

我完全失去了,我使用下面的AJAX將數據發佈到PHP並回顯「1」。但是,代碼無法進入「if(result == 1)」代碼塊。它總是進入我試圖提醒(結果)的ELSE塊。它顯示1沒有任何問題。爲我糟糕的解釋道歉。任何幫助深表謝意。PHP返回AJAX調用但代碼語句無法識別

$.ajax({ 
      url: $form.attr('action'), 
      type: 'POST', 
      data: $form.serialize(), 
      success: function(result) { 
       // ... Process the result ... 
       //alert(result); 

       if (result=="1") 
       { 
       swal({ 
        type: "success", 
        title: "Congratulation!", 
        text: "Please check your email inbox", 
        animation: "slide-from-top", 
        showConfirmButton: true 
        }, function(){ 

        var username = $("#username").val(); 
        var password = $("#password").val(); 


       }); 



       } 

       else 
       { 
       //alert(result); 
       swal({ 
        type: "error", 
        title: "", 
        text: result, 
        animation: "slide-from-top", 
        showConfirmButton: true 
       });  



       } 




      } 

     }); 

我的PHP代碼是如下:

if($dum=="TRUE") 
{  

    $password2 = $_POST['password2']; 
    $fullname = $_POST['fullname']; 
    $country = $_POST['id_country']; 
    $mobile = $_POST['mobile']; 
    $email = $_POST['email']; 
    $agent = $_POST['agent']; 
    $term = $_POST['term']; 

$sql = "INSERT INTO usercabinet (username, password, password2, fullname, country, mobile, email, agent, term, emailconfirm, identityconfirm, feeds) 
VALUES ('$username', '$password', '$password2', '$fullname', '$country', '$mobile', '$email', '$agent', '$term', '0', '0', 'Welcome to Our New Cabinet')"; 

if ($conn->query($sql) === TRUE) { 
    // "New record created successfully, Success!!<br>"; 

    $_SESSION['username'] = $username; 
    $_SESSION['fullname'] = $fullname; 
    $_SESSION['country'] = $country; 
    $_SESSION['mobile'] = $mobile; 
    $_SESSION['email'] = $country; 
    $_SESSION['term'] = $term; 
    $_SESSION['emailconfirm'] = 0; 
    $_SESSION['identityconfirm'] = 0; 
    $_SESSION['feeds'] = "Welcome to Cabinet"; 


    echo "1"; 

} 

可能是什麼故障的可能原因是什麼?

+0

'的console.log(結果);',看看你會得到什麼 – darham

+0

@ mega6382 。謝謝你的回覆..你能指導我如何檢查尾隨空間嗎?我試圖修改echo「1」到$ result = 1; echo $ result;但它仍然失敗..我是新來的.. –

+0

請檢查「結果」的數據類型以下 alert(typeof result); –

回答

1

嘗試以下操作:

result = trim(result); 
if(result == 1){ 

這將從字符串中刪除任何尾隨空格。或者,您可以確保在<?php ?>標籤之後或之前沒有空格。或者更好的是,你可以從PHP就像提交json響應:

$result = ['status' => 'success']; 
echo json_encode($result); 

而在你的JS是這樣的:

$.ajax({ 
    url: $form.attr('action'), 
    type: 'POST', 
    data: $form.serialize(), 
    dataType: 'json', 
    success: function(result) 
    { 
     if (result.status=="success") 
    } 
});