I’m building a live chat application with rooms for my assignment. Everything is going great so far, but I’m having trouble properly retrieving the latest chat messages from the database. The messages table has the following fields:
| m_id | u_id | r_id | message | sent |
m_id is the primary key. u_id and r_id are foreign keys to other tables to reference the user who sent the message and the room they sent the message to. The sent field has data in PHP’s microtime(true) format:
1326174129.977
I’ve built my AJAX script to retrieve messages from the database and it looks like this:
function getMessages() {
var d = new Date();
$.post("/ajax/getmessages.php", {roomID: roomID, timestamp: timestamp}, function(resp) {
resp = $.parseJSON(resp);
for(x in resp) {
$('#chat-holder ul').append('<li>[' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '] <strong>' + resp[x].u_id + '</strong>: ' + resp[x].msg + '</li>');
$("#chat-holder").scrollTop($("#chat-holder")[0].scrollHeight);
}
});
}
The getMessages function runs once a second, and then when it retieves data back from the getmessages.php script it loops through the JSON encoded response and ads list items to the chat frame. Pretty simple.
The problem is, it retrieves all messages sent to the room, not just the ones that have been sent since the last time the user polled for the latest messages. So I end up with every message that’s been sent in the chat being added to the chat frame every second.
The only thing I’ve come up with is to store a timestamp of the last time the user requested the messages, and then use that in my backend PHP script somehow. Unfortunately, I can’t quite get my head around how to implement it.
Any help is greatly appreciated, thank you.
Given that the idea isn’t so much to get all messages after a given time so much as to get all messages since the previous batch of messages, I think it’d be easier to do this based on your message table’s primary key rather than the timestamp field. Create a client-side variable to note the highest (known) id so far:
Then when you make your ajax request pass that id through to the PHP:
Then in your PHP:
In the ajax success handler you then update
highestMessageIdwith the id from the last record in the new batch.Of course this assumes that your table uses a standard numeric key where records added later have a higher key than records added earlier…
EDIT: Now that I think about it exactly the same procedure would work with the timestamp field too. When I started writing the above I thought there was some reason why timestamp wouldn’t work, but I think I was just confusing myself worrying about a non-issue (I was thinking about the times of the ajax requests rather than the timestamp on the records).