I am using ajax to fetch a string from a PHP script. The string is in the format of a JSON array consisting of multiple objects.
I can successfully access the objects, but I have no luck when using a loop. I need to access the objects in reverse order.
AJAX STRING RESPONSE:
{
"messages": [{
"username": "John",
"message": "Hello!",
"age": 32,
},
{
"username": "Bob",
"message": "Awesome day",
"age": 26,
},
{
"username": "Sarah",
"message": "How are you?",
"age": 19,
}
]
}
JAVASCRIPT:
var messageList = JSON.parse(ajax.responseText);
var message_count = messageList.messages.length;
while (message_count >= 0) {
alert(messageList.messages[message_count].username);
message_count -= 1;
}
I basically need the alerts to be in the order: Sarah Bob John I can access the array when I do something like: alert(messageList.messages[0].username);
It only seems to fail when I use the message_count variable. I have searched many hours for similar problems but found no success. Thank you in advance!
Your array has length 3, but arrays are indexed from zero, so you need to subtract 1 from your length total for the loop to work (messages[3]
doesn't exist).
var message_count = messageList.messages.length - 1;
The loop will go from 2 to 0 and give you the correct output.
try this:
$.getJSON( url, function( data ) {
var messages = data.messages || {};
$.each(messages,function(key,info){
console.log(info.username);
console.log(info.message);
console.log(info.age);
});
});