2015-05-04 24 views
2

我需要關於此代碼的幫助。如果請求的庫存項目(數據庫)小於他的請求(數量),我想動態禁止用戶添加到購物車。將欣賞,如果我能知道我錯在哪裏,可能有人正確的爲我。使用ajax動態更新用戶選擇

HTML表單

<form action="cart.php?adm_id=<?php echo urlencode($patient["adm_id"]);?>" method="post" name="CartForm" target="_self"> 
<p>Product Name:<select name="prod_name" size="1" id="prod_name"> 
<option value="Select">Select</option> 
<?php 
while ($line = mysqli_fetch_array($query, MYSQL_ASSOC)) { 
?> 
<option value="<?php echo $line['prod_name'];?>"> <?php echo $line['prod_name'];?> </option> 
<?php } ?> 

</select></p> 
<p>Quantity:<input type="number" name="qty" id="qty" size="30" required="required"/></p> 
<input name="submit" type="submit" value="Add to Cart" id="btn"/> | <input name="reset" type="reset" value="Cancel" /> 

Ajax代碼:

<script src="javascript/jquery-2.0.3.js"> 
</script> 
<script type="text/javascript"> 
$(document).ready(function(ex) { 
    //$('#stock').load('pharmacy_summary.php'); 
$('#qty').change(function(){ 
var prod_name = $('#prod_name').val(); 
var qty= $('#qty').val(); 
$.ajax({ 
    url: 'confirmStock.php', 
    data:{prod_name: prod_name, qty: qty}, 
    success: function(e){ 
     if(e == 'true'){ 
      /*if the quantity is greater than the stock*/ 
      alert('stock Item is lower to your request, reduce it'); 
      $('#btn').prop('disabled', true); 
     }else{ 
      $('#btn').prop('disabled', false); 
     } } 
})});  
}); 
</script> 

PHP/mysqli的代碼:(ConfirmStock.php)

<?php require_once("/includes/db_connection.php");?> 
<?php require_once("/includes/functions.php");?> 
<?php 
if(isset($_GET['prod_name'])){ 

    $getProd = $_GET['prod_name']; 
    $getQty = $_GET['units']; 

global $connection; 
    $val = "SELECT * FROM pharmacy_stock_tab WHERE prod_name='".$getProd."'"; 
    $conf = mysqli_query($connection,$val); 
    $fetchVal = mysqli_fetch_array($conf); 
    $stock = $fetchVal['units']; 
    if($getQty>$stock){ 
    return $stock; 
    }else{ 
    return $stock; 
    } 

} 

?> 
+1

一件事'MYSQL_ASSOC'必須'MYSQLI_ASSOC' - 你的API混合。 –

+0

然後在你的'cart.php?adm_id'你正在做一個GET方法,但沒有任何匹配,除了混合GET和POST。 if(isset($ _ GET ['prod_name'])){'should should be'if(isset($ _ GET ['adm_id'])){' –

+2

什麼不在你的代碼中工作? – SaidbakR

回答

0

你必須ç增加了您發送回覆的方式以及處理回覆的方式。改變ConfirmStock.php代碼 改變返回語句如下方式

$result = array(); 
if($getQty>$stock){ 
    $result['success'] = 'true'; 
    $result['stock'] = $stock; 
}else{ 
$result['success'] = 'false'; 
} 
header('Content-Type: application/json'); 
echo json_encode($result); 
die(); 

在阿賈克斯成功方法

success: function(response){ 

    if(response.success == 'true'){ 
     /*if the quantity is greater than the stock*/ 
     alert('stock Item is lower to your request, reduce it'); 
     $('#btn').prop('disabled', true); 
    }else{ 
     $('#btn').prop('disabled', false); 
    } } 
+0

我給它一個嘗試。但是用戶通過比數量更多的數據來擴展,直到數據庫現在正在顯示-value。任何進一步的援助 – Dave

+0

任何進一步的幫助,我想要一個解決這個任務,我已經完成了你的建議,但沒有工作。 – Dave

+0

你收到了什麼響應,並提醒響應成功,如alert(JSON.stringify(response)); –