使用ajax动态更新用户选择

时间:2015-05-04 13:05:51

标签: php ajax mysqli

我需要有关此代码的帮助。如果请求的库存项目(数据库)小于他的请求(数量),我想动态禁止用户添加到购物车。如果我能知道我错在哪里并且可能有人为我纠正它,我将不胜感激。

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 个答案:

答案 0 :(得分:0)

您必须更改发送响应的方式以及处理响应的方式。更改ConfirmStock.php中的代码 以下列方式更改return语句

$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();

在Ajax成功方法

   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);
    }    }