I really doubt my mind right now and am pretty confused.
I'm building a little chat application, just to expriment with some stuff...
For that, I have a MySQL Database with a table just storing the messages with an ID, the content of the message, the userid and a timestamp.
On the page to display the chat, I then do an ajax request to my backend, which returns the data from the database like so:
$messages = $db->exec('SELECT * FROM message ORDER BY ID DESC LIMIT 50');
echo json_encode($messages);
So what I'm getting from there the last 50 messages, encoded in JSON.
On the page, I then receive that and parse them:
messagesParsed = JSON.parse(messages);
So now, what I've got in that variable is this (shortened a bit)
[
{
"ID": "68",
"content": "oi",
"uid": "4",
"time": "2021-07-16 13:29:42"
},
{
"ID": "67",
"content": "io",
"uid": "4",
"time": "2021-07-16 13:29:42"
},
{
"ID": "66",
"content": "oibioboib",
"uid": "4",
"time": "2021-07-16 13:29:42"
},
{
"ID": "65",
"content": "iob",
"uid": "4",
"time": "2021-07-16 13:29:41"
},
{
"ID": "64",
"content": "b",
"uid": "4",
"time": "2021-07-16 13:29:41"
},
{
"ID": "63",
"content": "boi",
"uid": "4",
"time": "2021-07-16 13:29:41"
},
{
"ID": "62",
"content": "oibio",
"uid": "4",
"time": "2021-07-16 13:29:41"
}
]
Then, I'm looping through this array in reverse, with the goal to display the latest message at the very bottom of the page:
for(var i = messagesParsed.length; i>=0; i--){
message = messagesParsed[i];
console.log(message);
}
So far so good, I now got this as a result (stored in the message variable)
{
"ID": "32",
"content": "fn",
"uid": "4",
"time": "2021-07-16 13:29:24"
}
Here comes the strange part: I want to only display the content of the chat message (at first) and have tried like 20 different variations of getting the content, so within the for loop, I did something like:
console.log(message.content); console.log(message["content"]); console.log(message[content]);
And some other crazy stuff, but in the end, I'm not getting the console to output the value. Only thing I'm getting there is Cannot read property 'content' of undefined
What am I doing wrong? It's not like the first time I try to access something in a JS object, but it seems like I'm just completely lost on this one.
var i = messagesParsed.length - 1.