I am playing around with parsing JSON in jQuery and I am having trouble. I want to check the value of 'time' in the JSON object. Here is my trial function:
$.ajax({
url: 'do_chat.php5',
type: 'post',
data: ({'message':'','poster':poster,'logged_in':logged_in}),
dataType: 'json',
success: function(data) {
$.each(data, function(interval, message) {
if(message['time']) {
$('#chatWindow').append('<p>hi</p>');
}
});
}
});
The string being returned from my server looks like:
{"poster":"","message":"No messages!","time":1256084677}
I am not sure of the syntax of $.each. I am using PHP to encode the JSON string, which started life as a php assoc array. I'm sure my mistakes are plenty and any help is greatly appreciated!
Edit: follow up question - how do I make PHP generate a JSON array? At the moment I use this to generate the single object:
$messages = mysqli_fetch_assoc($new_res);
$msg = $messages["content"];
$who = $messages["poster"];
$time = $messages["time_added"];
$message = array(
'poster' => $who,
'message' => $msg,
'time' => $time
);
echo json_encode($message);
But if I were to get more than one row from my database query, how do I do that?