2016-03-24 26 views
0

&我有一個貨物接收數量字段。我想根據訂單表檢查收據表,並確保輸入的值不超過總訂單值。我有這樣的代碼在我的領域:使用JS在輸入上檢查mysql數據庫

<div class="pure-control-group">  
    <label for="rec_qty">Qty Received:</label> 
    <input type="text" name="rec_qty" id="rec_qty" onChange="receiptTotal()"></input> 
</div> 

JavaScript代碼:

function receiptTotal(){ 
    $.ajax({ 
     type: "GET", 
     url: "receipts.php?do=checkrec&id="+row.pur_ID, 
     //dataType: 'json', 
     success : function(data) { 
      // Here I want to do the comparisons of the two fields. 
      // If data.rec_qty + form.rec_qty > pur_qty then throw error. 
     } 
    }); 
} 

最後PHP代碼:

if($_GET['do'] == "checkrec") { 
    $rec = []; 
    //First get the receipts total for this ID 
    $getRows = $db->query(sprintf("SELECT sum(rec_qty) as total_qty, pr.pur_qty from receipts inner join purchases pr on rec_purID = pr.pur_ID WHERE rec_purID = '$groupid' GROUP BY pur_ID")) or SQLError(); 
    while($rec = $getRows->fetch_assoc()) { 
     $result[] = $rec; 
    } 
    echo json_encode($result); 
} 

我只是櫃面任何人想知道一個完整的新手。我真的很感激幫助!

+1

你在哪裏定義$ groupid?和你的url字符串不會工作。您需要&而不是$ – KyleK

+0

groupid在PHP文件中定義: – Nic

+0

我的json數組看起來像這樣: [{「total_qty」:「323」,「pur_qty」:「500」}] – Nic

回答

1

起初我以爲你問過如何在你的數據庫中做到這一點,但現在我看到你已經從你的服務器獲取數據並返回它。所以我現在會回答,希望它能代表你的意思。

function receiptTotal(){ 
    $.ajax({ 
    type: "GET", 
    url: "receipts.php?do=checkrec&id="+row.pur_ID, 
    //dataType: 'json', 
    success : function(data) { 
     var rec_qty = $('#rec_qty').val(); 
     if((data.rec_qty+rec_qty) > data.pur_qty){ 
      alert('Value is too high!!'); // or whatever error you want 
     } 
    } 
    }); 
} 

我要說的是,雖然.....你基本上是射擊與數據庫的要求,每次現場變化而服務器請求。這是非常低效的。您應該只加載一次數據,然後在本地參考該檢查。但我會讓你自己想出來:)