I'm trying to create a simple Point of sale using PHP, and I want to add data in my table everytime I search and submit the barcode. The problem with my code, it only runs once, it appends the first data I add but for the next nothing happens, here is my HTML
<form class="" action="" id="pos_data" method="post">
<input type="text" name="txtSearch" placeholder="barcode" autofocus>
</form>
<table id="pos-items">
<thead><tr>
<td>Product Name</td>
<td>Quantity</td>
<td>Unit</td>
<td>Price</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
and this my script
$('#pos_data').submit(function() {
$.ajax({
url: 'processpos.php',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(newContent) {
$('#pos-items tbody').append(newContent);
}
});
return false;
barcodeenter();
});
function barcodeenter(){
document.querySelector('#txtSearch').addEventListener('keypress', function (e){
var key = e.which || e.keyCode;
if (key === 13) { // 13 is enter
console.log(document.getElementById("txtSearch").value);
document.getElementById("txtSearch").value = "";
}
});
}
and my PHP file
include 'conn_db.php';
$product_id = $_POST['txtSearch'];
$sql = "SELECT * FROM producttbl WHERE product_id ='".$product_id."'";
$records = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($records)){
echo "<tr><td>".$row['product_name']."</td><td>1</td><td>".$row['product_unit']."</td><td>".$row['product_price']."</td></tr>";
}
all in the code works for the first product but when i try to add another nothing happens. Is there anything I'm missing out here?
Remove the function barcodeenter()
and replace with document.getElementById("pos_data").reset();
$('#pos_data').submit(function() {
$.ajax({
url: 'processpos.php',
type: 'POST',
dataType: 'html',
data: $(this).serialize(),
success: function(newContent) {
$('#pos-items tbody').append(newContent);
}
});
//barcodeenter();
document.getElementById("pos_data").reset();
return false;
});
Try to change
while($row = mysqli_fetch_assoc($records)){
echo "<tr><td>".$row['product_name']."</td><td>1</td><td>".$row['product_unit']."</td><td>".$row['product_price']."</td></tr>";
}
To
$rowdata ='';
while($row = mysqli_fetch_assoc($records)){
$rowdata .= "<tr><td>".$row['product_name']."</td><td>1</td> <td>".$row['product_unit']."</td><td>".$row['product_price']."</td></tr>";
}
echo $rowdata;
I encountered the same issue a long time ago,
what i did was,
instead of returning html tags as response,
make it return json data, it solved my problem,
$.ajax({
url: 'processpos.php',
type: 'POST',
dataType: 'json',
data: id,
success: function(newContent) {
$.each(response, function(a,b){
$('#pos-items tbody').append("<tr><td>"+b.field+"</td></tr>");
})
}
});
Try this.
Change
$rowdata ='';
while($row = mysqli_fetch_assoc($records)){
$rowdata .= "<tr><td>".$row['product_name']."</td><td>1</td> <td>".$row['product_unit']."</td><td>".$row['product_price']."</td></tr>";
}
echo json_encode($rowdata);