TheOrdinaryGeek TheOrdinaryGeek - 1 month ago 9
jQuery Question

AJAX Response and PHP Loop

I am using PHP to retrieve some records from a MySQL database, I would like to send these to my AJAX and loop through them, in order to

prepend
rows to an existing table.

However I can only see the last (most recent) record returned from my query. Could someone please point out where I am going wrong?

AJAX:

$.ajax({
type: "POST",
url: 'feed.php',
data: {lastSerial: true},
dataType: 'json',
success: function(data){
console.log(data); // logs `{Direction: "O", CardNo: "02730984", SerialNo: 20559303}`
$.each(data, function(key, value) {
// here I want to loop through the returned results - for example
$("#transactionTable").prepend('<tr><td>'+ SerialNo +'</td><td>'+ CardNo +'</td><td>'+ Direction +'</td></tr>');
});
}
});


feed.php

if(isset($_POST['lastSerial']) && $_POST['lastSerial'] == true) {
$query = "SELECT TimeStamp, Direction, CardNo, SerialNo FROM Transactions";
// this query returns approx. 20 results
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$data["Direction"] = $row['Direction'];
$data["CardNo"] = $row['CardNo'];
$data["SerialNo"] = $row['SerialNo'];
}
echo json_encode($data);
}


Also in my PHP, should I be using a
while
or
if
statement?

Answer Source

You're using a single $data object and resetting its contents each time. You want to build an array of objects:

$data = array();

while($row = $result->fetch_assoc()) {
  $data[] = array( 
    "Direction" => $row['Direction'],
    "CardNo"    => $row['CardNo'],
    "SerialNo"  => $row['SerialNo']
  );
}

echo json_encode($data);

Followed by:

// ...
success: function(data){
    $.each(data, function(key, value) {
        // here I want to loop through the returned results - for example
        $("#transactionTable").prepend('<tr><td>'+ value.SerialNo +'</td><td>'+ value.CardNo +'</td><td>'+ value.Direction +'</td></tr>');
    });
   }