2015-08-14 67 views
-1

我在JavaScript函數中編寫了ajax。該代碼是爲什麼ajax代碼與php連接不起作用?

function getValidate(checkID) 
{ 
    alert(checkID); 
    $.ajax({     
     type: 'post', 
     url: 'checkval.php', 
     datatype: 'json', 
     data: {checkID : checkID}, 
     success: function (response) { 

      if (response === "OK"){ 
      alert("Validation Successed."); 

     }else if(response === "NG"){ 
      alert("Check Already Exists."); 
     } 
    }, 
     error : function(err, req) { 
     alert("Error Occurred"); 
    } 
    }); 
} 

此代碼僅輸出「發生錯誤」。

連接的PHP腳本是

<?php 
     echo("welcome"); 
    $check   = $_POST['checkID']; 
    $host  = 'localhost'; 
     $database = 'database'; 
     $username = 'root'; 
     $password = 'root'; 

    $dbc = mysqli_connect($host,$username,$password,$database); 

     $checkno = $check; 
     $sql = "select claimno from check_details where checkno = $checkno"; 
     $result = mysqli_query($dbc,$sql); 
     $rows = mysqli_num_rows($result); 
     if($rows != 0) 
     { 
         echo "NG"; 
     } 
       else 
       { 
         echo "OK"; 
       } 
?> 

在調用不執行JavaScript函數的PHP文件的時間......

請給我的想法,成功的話.... .......

+1

你會得到什麼錯誤? – evolutionxbox

+0

我得到了「發生錯誤」這個作爲輸出... –

+0

作爲警報消息 –

回答

1

還設置數據類型來JSON所以響應的數據必須是json type

$.ajax({ dataType:"json"}); 

在php中,存儲導致一個變量並返回json_encode

<?php 
    echo("welcome"); 
$check   = $_POST['checkID']; 
$host  = 'localhost'; 
    $database = 'database'; 
    $username = 'root'; 
    $password = 'root'; 

$dbc = mysqli_connect($host,$username,$password,$database); 

    $checkno = $check; 
    $sql = "select claimno from check_details where checkno = '$checkno'"; //use single quote 
    $result = mysqli_query($dbc,$sql); 
    $rows = mysqli_num_rows($result); 
    if($rows != 0) 
    { 
        $res = "NG"; 
    } 
    else 
    { 
        $res = "OK"; 
    } 
echo json_encode($res); 
?> 
0

看來php腳本運行不正常。

使用try and catch進行調試,並查看輸出結果。

+0

php腳本沒有任何錯誤或警告正在工作。完整的問題是ajax ......它沒有連接到php腳本...... –

+0

你能通過網絡瀏覽器訪問php腳本嗎? –

+0

是否需要在Ajax腳本中進行任何更改.... –

2

試試這個:發生

if($rows != 0) 
{ 
    $return = "NG"; 
} 
else 
{ 
    $return = "OK"; 
} 


echo json_encode($return); 
+0

它不工作烏鴉.... ....它顯示爲正常的「發生錯誤」....... –

+0

我試過這個....它還沒有工作 –

+1

請檢查checkval.php的路徑 –

1

你得到的錯誤,因爲下面的代碼。嘗試記錄一些有意義的內容來將它們合併

error : function(err, req) { 
     alert("Error Occurred"); 
    } 

請嘗試以下代碼以獲取錯誤的線索

error: function(xhr, status, error) { 
    var err = eval("(" + xhr.responseText + ")"); 
    alert(err.Message); 
} 

參考:Take a look at this query

相關問題