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!