jquery - AJAX Response and PHP Loop -
i using php retrieve records mysql database, send these ajax , loop through them, in order prepend
rows existing table.
however can see last (most recent) record returned query. please point out 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 want loop through returned results - 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 transactions"; // 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 php, should using while
or if
statement?
you're using single $data
object , resetting contents each time. want build 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 want loop through returned results - example $("#transactiontable").prepend('<tr><td>'+ value.serialno +'</td><td>'+ value.cardno +'</td><td>'+ value.direction +'</td></tr>'); }); }
Comments
Post a Comment