我想添加我在div中获得的结果

时间:2016-02-27 20:28:24

标签: javascript php jquery html ajax

我想要做的是从表中获取数据,添加并显示它们。

我有下表。

Table

我在文本框中输入输入并将结果输入div。我正在使用append来显示结果。现在显示结果后,我想添加价格并显示它。

输出

Output

我的主要文件

<!DOCTYPE html>
<html>
<head>
    <title>Products</title>
    <p align="center" style="font-size:20px" > Scan the Barcode of the    Product  </p>
    <link href="mystyle.css" rel="stylesheet">
</head>
<body>

        <input type="text" id="item" style="text-align:centre" placeholder=" Barcode ID" autofocus /> <!--text box -->

        <div id="item-data"></div>

        <script src="js/jquery-2.2.0.min.js"></script> <!--jquery link-->
        <script src="js/global.js"></script> <!--linking event file-->

</body>
</html>

我的javascript文件

$(function(){


//press enter on text area..

$('#item').keypress(function (event) {
var key = event.which;
if(key == 13)  // the enter key code
{

var item = $('input#item').val();    // retreiving the value from the item
    if ($.trim(item) != ''){            //send this to php file but if its   empty or spaces(trim) are there dont send it//
        $.post('ajax/name.php',{id:item}, function(data){   //using post  method sending to the father(name.php), sending the data through the file item
            $('div#item-data').append(""+data+"</br>"); // grabing the data and displaying it

});

}

$('#item').val('');
}
});

});

name.php文件

<?php

require '../db/connect.php';

$id= $_POST['id']; // your post variable
$sql = "SELECT BarcodeID, shirts, price FROM clothes WHERE BarcodeID=".mysqli_real_escape_string($con,$id);

$result = mysqli_query($con,$sql) or die(mysqli_error($con));

if(mysqli_num_rows($result)>0)
{
    while($row = $result->fetch_assoc())
    {
        echo " " . $row["BarcodeID"]. " shirt color:  " . $row["shirts"]. " price: " . $row["price"];
    }
}
else
{
        echo "ID not found, Please Scan again";
}
mysqli_close($con);

?>

2 个答案:

答案 0 :(得分:1)

试试这个:

if(mysqli_num_rows($result)>0)
{
    $sum = 0;
    while($row = $result->fetch_assoc())
    {
        echo " " . $row["BarcodeID"]. " shirt color:  " . $row["shirts"]. " price: " . $row["price"];
        $sum = floatval($sum) + floatval($row["price"]);

       // or $sum = $sum + (int)($row["price"]);
    }
}

echo $sum; 

答案 1 :(得分:0)

最简单的方法是在你已经得到的那个循环中添加一个变量......然后追加它。

$total += $row['price']

...

echo $total

你可以执行另一个SQL语句来获取它。但我不明白这一点。