I have this php code that is call using jQuery ajax that queries a database and gets results and then json encode the results
//$rows is another query
foreach($rows as $row) {
$sql = 'SELECT field1, field2 FROM table WHERE field1= :field';
$stmt = $db->prepare($sql);
$stmt->bindValue(':field', trim($row['field_1']));
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($array);
}
The outputting json looks like this
[{"field1":"J1","field2":"0088","field3":"2928868"}][{"field1":"J2","field2":"0171","field3":"2928868"}][{"field1":"J2","field2":"0249","field3":"2928868"}]
The problem I'm getting is processing it in the Ajax response. What I would like to do i s loop through each of the array/rows and display the data but the responseText shows an error.
I thought it should look this but i don't know for definite.
[{"field1":"J1","field2":"0088","field3":"2928868"},{"field1":"J2","field2":"0171","field3":"2928868"},{"field1":"J2","field2":"0249","field3":"2928868"}]
My question is, am i doing the json_encode correctly and how do i output each of the rows?
$.ajax({
type: "POST",
url: "check.php",
data: { order: order },
dataType: "json",
cache: false,
success: function(response) {
if(response.length != 0) {
//output results here
}
else {
$('#foo').text('Order number not found!!');
}
// set the focus to the order input
$('#order').focus().val('');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('An Ajax error was thrown.');
console.log(XMLHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});