I’m making a conversation system where 2 people can chat with each other. I’ve made an AJAX function which updates the DIV box containing the messages every 2 seconds.
This is working as intended, after a user have written a message. Why isn’t the AJAX call being run right away?
// SET AUTORUN updateMessages() EVERY 2 SECONDS
$(document).ready(function() {
var interval
window.onload = function(){
interval = setInterval('updateMessages()', 2000);
};
});
// UPDATE #mail_container_conversation
function updateMessages() {
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/ajaxupdate/<?php echo $user; ?>",
data: dataString,
success: function(data){
$("#mail_container_conversation").html(data);
}
});
}
// SEND NEW MESSAGE
$(function(){
$("#mail_send").submit(function(){
dataString = $("#mail_send").serialize();
$.ajax({
type: "POST",
url: "<?php echo site_url(); ?>mail/send",
data: dataString,
success: function(data){
updateMessages();
$(".mail_conversation_answer_input").val('');
}
});
return false;
});
});
You should provide functions instead of strings to
setTimeout/setIntervalfunctions. And also there’s no need for you to set interval on window load event. You can just keep it as part of DOM ready:Everything else seems to should work as expected as long as your posback work when no data is being received (ref
dataString).I hope you do realise that you’re using implied globals and understand why that may be a big problem (ref
dataStringagain).How I would rewrite your code
I would rewrite your whole code into the following that removes implied global variable
dataString, doesn’t pollute global scope with additional functions and usessetTimeoutinstead of interval which may in some cases be problematic (although in your case since it’ only runs every 2 seconds it shouldn’t be a problem if there’s no additional very complex client-side script execution)I’ve kept everything within function closure local scope:
This code requires your server side (processing on
/mail/send) to understand that when nothing is being posted (no data) that it doesn’t add empty line in the conversation but rather knows that this is just an update call. This functionality now uses only one server-side URL and not two of them. If you’d still require two, then this code should do the trick: