通过Javascript验证PHP变量

时间:2015-04-03 05:14:45

标签: javascript php html sql variables

我希望将我的PHP代码中的一个变量传递给我的Javascript代码以验证数字。我正在创建一个购物车场景,我有一个变量'in_stock',它指定了产品可用的库存量。如果我输入的金额大于'in_stock'可用,我需要抛出一个错误。这就是我现在所拥有的:

Java脚本

   <script language="javascript">
  function numCheck() 
  {
        var enteredChar = document.getElementById('add_value').value;
        var stockavailable ="<?php echo $stock?>";

    //To check if a non-numerical value is entered
    if (isNaN(enteredChar)) 
    {
        alert("Not a Number!");
        return false;
    }
    //To check if the input is empty
    if (enteredChar=="")
    {
        alert("Empty!");
        return false;
    }
    //To check if the amount entered is not greater than the amount in stock
 if (enteredChar > stockavailable)
    {
        alert("Not enough in stock");
        return false;
    }

 }  
   </script>

这一切都在我的PHP调用数据库并在屏幕上返回值时发生。如下:

PHP

$product_id =(int)$_GET['product_id'];

$username = "potiro";
$password = "pcXZb(kL";
$hostname = "rerun";

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
 or die("Unable to connect to MySQL");


//select a database to work with
$selected = mysql_select_db("poti",$dbhandle)
  or die("Could not select examples");

//execute the SQL query and return records
$result = mysql_query("SELECT * FROM products where product_id=$product_id");

echo '<form name="form1">';
echo '<table class="Grocery-table">'; 

while($row = mysql_fetch_array($result))
{

$stock =$row['in_stock'];
$product_id = $row['product_id'];

  echo "<tr><td><b>Product ID</b></td>"; 
  echo "<td>";  
  echo $product_id;
  echo "</td></tr>";
  echo "<tr><td><b>Product Name</b></td>";
  echo "<td>";
  echo $row['product_name'];
  echo "</td></tr>"; 
   echo "<tr><td><b>Unit Price</b></td>";
  echo "<td>";
  echo $stock;
  echo "</td></tr>"; 
  echo "<tr><td><b>Unit Quantity</b></td>";
  echo "<td>";
  echo $row['unit_quantity'];
  echo "</td></tr>"; 
  echo "<tr><td><b>In Stock</b></td>";
  echo "<td>";
  echo $row['in_stock'];
  echo "</td></tr>";
  echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart"></input></td></tr>';
  echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';
 }
echo "</table>"; 
echo "</form>";

mysql_close($dbhandle);
?>

1 个答案:

答案 0 :(得分:2)

将您的股票价值添加到隐藏的输入值stock_value

 echo '<tr><td><b>Add</b></td><td><Input type="text" id="add_value" name="cart"  ></input><Input type="hidden" id="stock_value" name="stock_value"  value="'.trim($stock).'"></input></td></tr>';
 echo '<tr><td></td><td><input type="submit" value="Submit" onclick="return numCheck()"></td></tr>';

在javascript中

<script language="javascript">
  function numCheck() 
  {
        var enteredChar = document.getElementById('add_value').value;
        var stockavailable =document.getElementById('stock_value').value;