Trouble parsing JSON with $.each
I am using $.ajax to fetch a JSON_encoded object from a PHP script. This returns a JSON array which I know I need to use $.each to parse, but I'm having problems getting it to work. Here is the PHP that creates the JSON:
-
if(mysqli_num_rows($new_res) > 0) {
$messages = array();
while($message_data = mysqli_fetch_assoc($query_res)) {
$message = array(
'poster' => $message_data['poster'],
'message' => $message_data['message'],
'time' => $message_data['time']
);
$messages[] = $message;
}
echo json_encode($messages);
} else if(mysqli_num_rows($new_res) == 0) {
$message = array(
'poster' => '',
'message' => 'No messages!',
'time' => 1
);
echo json_encode($message);
}
And here is the jQuery where I try to use it:
-
$.ajax({
url: 'do_chat.php5',
type: 'post',
data: ({'poster':poster,'logged_in':logged_in}),
dataType: 'json',
success: function(data) {
$.each(data, function(messageIndex, message) {
if((parseInt(message['time']) > parseInt($('#chatWindow :last-child > span').html()))) {
$('#chatWindow').append('<div class="poster">'+message['poster']+'</div><div class="message"><span>'+message['time']+'</span>'+message['message']
+'</div>');
}
});
}
});
I have successfully unpacked a single-dimensional array without the $.each function, but the PHP script will return several rows from MySQL. Any help would be very much appreciated![/code]