I have live chat on my website and right now it's just polling. I want to get with the times and replace this with a node.js version. I've been making good progress but am now stuck on something that appears to just be a syntax issue.
So what I'm doing is when the user first comes to my site, I want to show them the most recent chat that's in the mysql database. So it will be rows of
time user their message
I'm sending this data on user connect from my app.js file with
io.sockets.on('connection', function (socket) {
//Make connection to mysql
connection.query('select values from my_table limit 5', function(err, rows, fields) {
user_info = new Array();
for (i = 0; i < rows.length; i++) {
user_info[i] = new Array();
user_info[i]['time'] = rows[i].time;
user_info[i]['user'] = rows[i].user;
user_info[i]['their_message'] = rows[i].their_message;
}
io.sockets.emit('some_event_tag', user_info);
});
So this works, except that when I try and access this data under the function associated with "some_event_tag", it appears my syntax is off because I'm not getting the information. So on the client, I'm trying to access the data with
some_event_tag: function(data) {
var msg = '';
for (i = 0; i < data.length; i++) {
msg = $('<div class="msg"></div>')
.append('<span class="name">' + data[i]['user'] + '</span>: ')
.append('<span class="text">' + data[i]['their_message'] + '</span>');
$('#messages')
.append(msg);
msg = '';
}
},
but for whatever reason I'm getting "undefined". On the server side, if I change
io.sockets.emit('some_event_tag', user_info);
to something like
io.sockets.emit('some_event_tag', user_info[0]['user']);
I can access this value on the client (by just saying "data"). Of course, in this case, I'm only passing one value. Not what I want. On the client side, I can also correctly see that five array elements are being passed. In other words, data.length is correctly set to 5. However, I can't actually figure out the syntax to access the data on the client side. Isn't this just typical javascript arrays? I'm a little stumped at this point and google didn't help me this time. Any help you guys can give would be greatly appreciated.