检查输入数量是否大于数据库中的可用数量

时间:2016-11-30 07:59:59

标签: javascript php html ajax

我想要做的是检查文本框输入数量是否大于数据库中的可用数量。警报应显示onclick()按钮的ADD

ADD按钮

<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); resetform(); checkQty();">ADD</button>

checkQty()功能

function checkQty() { 
    //Grab current forms input field values.
    var txtQuantity = document.getElementById("txtQuantity").value;
    var listItemName = document.getElementById("listItemName").value;

    //Connect to database and verify Quantity Ordered isnt greater than Quantity In Stock.
    $.ajax({
        type: "POST",
        url: "/pms/includes/functions/qty_check.php",
        data: 'listItemName=' + listItemName + '&txtQuantity=' + txtQuantity,
        }).responseText;            
}

qty_check.php

<?php

error_reporting(E_ALL );
ini_set('display_errors', 1);

//Start the Session
if(!isset($_SESSION)) 
{ 
   session_start(); 
} 

include_once("../../config.php");
require __DIR__."../../dbutil.php";

if(!empty($_POST['txtQuantity'])){$qty =  $_POST['txtQuantity'];}
if(!empty($_POST['listItemName'])){$item =  $_POST['listItemName'];}

$results = mysqli_query($connection, "SELECT * FROM purchase_items WHERE item_id= ".$_GET['listItemName']"");

$row = mysqli_fetch_assoc($results);
{
    $tb_qty=$row["avail_qty"];
}

if($tb_qty < $qty){ ?>

<script type="text/javascript">
    alert("Quantity exceeds the stock limit");
</script>

<?php
}
?>

我尝试了很多,但我无法解决这个问题。感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您不应该直接从ajax调用打印出html。你应该回应一些你可以在前端解析的json来获取信息。使用

echo json_encode(['key' => 'value'])

这是您的代码,稍作修改。我在ajax查询和ajax请求完成时调用的dataType函数中添加了done

function checkQty() { 
  //Grab current forms input field values.
  var txtQuantity = document.getElementById("txtQuantity").value;
  var listItemName = document.getElementById("listItemName").value;

  //Connect to database and verify Quantity Ordered isnt greater than Quantity In Stock.
  $.ajax({
    type: "POST",
    url: "/pms/includes/functions/qty_check.php",
    dataType: 'json',
    data: {
      listItemName: listItemName,
      txtQuantity: txtQuantity
    }
  }).done(function(response){
    alert('check your console!')
    console.log('this is the response', response.available);
  })
}

<强> qty_check.php

<?php

error_reporting(E_ALL );
ini_set('display_errors', 1);

//Start the Session
if(!isset($_SESSION)) 
{ 
   session_start(); 
} 

include_once("../../config.php");
require __DIR__."../../dbutil.php";

if(!empty($_POST['txtQuantity'])){$qty =  $_POST['txtQuantity'];}
if(!empty($_POST['listItemName'])){$item =  $_POST['listItemName'];}

$results = mysqli_query($connection, "SELECT * FROM purchase_items WHERE item_id= ".$_GET['listItemName']"");

$row = mysqli_fetch_assoc($results);
{
    $tb_qty=$row["avail_qty"];
}
// echo out some json to send to the front end
echo json_encode(['available' => $tb_qty < $qty]);
?>