Reputation: 5193
So I'm trying to make a chat program in JavaScript using AJAX, and PHP. I am currently updating the chat like this, and I'm sure it's very hard on my server:
<div id="messages">[no messages]</div>
This is whats in the file called ajax-load-messages.php
<?php
$sql_posts_result = mysql_query("SELECT Post FROM Posts ORDER BY Date ASC LIMIT 50", $db) or die("Can't load post"."<br/>".mysql_error());
if(!empty($sql_posts_result)){
while($row = mysql_fetch_row($sql_posts_result)){
echo '<div class="message-post">'.$row[0].'</div>';
}
}
?>
and that's called by this javascript:
setInterval(function(){
$('#messages').load('/ajax-load-messages.php');
}, 3000);
So every 3 seconds I load the last 50 messages to the #messages div. I know there's a way to handle this that isn't even like 10% as resource intensive, but I don't know where to start. How can I handle this better?
Upvotes: 1
Views: 128
Reputation: 630
These would be my suggestions to handle your chat system better:
1) I would suggest to use a chained-setTimeout instead of setInterval
Why? Suppose the load takes longer than 3 seconds. Then setInterval will beat that and cause more than 1 XML HTTP Request to happen, causing a strain in the browser.
This is how a chained setTimeout would look like in your example:
setTimeout(function loadMessages() {
$("#messages").load('/ajax-load-messages.php', function onLoadMessagesComplete(responseText, textStatus, xmlHttpRequest) {
setTimeout(loadMessages, 3000);
});
}
2) Instead of writing HTML in ajax-load-messages.php, you could respond back with a JSON object json_encode()
. Then if you keep track of each chat instance's messages in an array that are currently displayed, then you can figure out if there is a new message or not (developerwjk's answer is a good suggestion). This way, you don't have to reload the DOM every 3 seconds (regardless if there was a new message or not). Of course, you would need to keep aware of the memory usage in the browser though.
===
Usually chat systems (like the Facebook, Google+) use pushing systems rather than polling. The server pushes to the client if there is a new message. This reduces the number of requests to the server, but it could be more difficult to implement.
Upvotes: 0
Reputation: 8659
Give the table an int autoincrement id. Keep track of the highest id received (in the session maybe), and on next poll only look for ids higher than that (i.e. only records created since last poll).
Upvotes: 2