Reputation: 884
I am trying to loop over a JSON output from PHP and assign a list item to each index.
Im having two separate issues.
PHP
$data= json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
echo json_encode($data);
JSON
"[
{\"id\":\"1\",\"user_id\":\"1\",\"message\":\"MSG 1\"},
{\"id\":\"2\",\"user_id\":\"1\",\"message\":\"MSG 2\"},
{\"id\":\"3\",\"user_id\":\"1\",\"message\":\"MSG 3 \"},
]"
jQuery
$.ajax({ url: 'chat.php',
dataType: 'json',
type: 'post',
error: function(statusCode, errorThrown) {
updateError(statusCode, errorThrown);
},
success: function(data){
$.each(data, function() {
$.each(this, function(k, v) {
$('<li data-msgid="'+data.id+'">' + data.user_id + '::' + data.message + '</li>').appendTo('#chat_area');
});
});
}
});
Im using ajax call rather than json as I will eventually be passing data in this same function. Any help is much appreciated.
Upvotes: 1
Views: 52
Reputation: 91744
You are encoding twice:
$data= json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
echo json_encode($data);
Remove the first one and only encode the final data:
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
...
echo json_encode($data);
Upvotes: 2