Reputation: 152
I'm new in web programming and I'm learning javascript and jquery ajax now..
this is my javascript code. refresh variable is interval for refresh chat (get chats from database and showing them in the chat container) every 2secs. I want to stop the interval and then append a new message to the container after I submit the message.
the problem is when I pressed enter, new chat append to the container, yes. but suddenly the container is refreshed and replace that new message with records from database ( so it's gone (clearInterval is not working yet) ). Then clearInterval is working when function finished.. why? why? :(
var oldscrollHeight;
var newscrollHeight;
var refresh;
function refreshChats(){
oldscrollHeight = $(".chatContainer").prop("scrollHeight");
$.ajax({
url:"get_chats.php",
cache: false,
success: function(html){
$(".chatContainer").html(html);
//Auto-scroll
newscrollHeight = $(".chatContainer").prop("scrollHeight");
if(newscrollHeight > oldscrollHeight){
$(".chatContainer").prop({ scrollTop: $(".chatContainer").prop("scrollHeight") });
}
}
});
}
$("document").ready(function(){
refresh = setInterval(refreshChats,2000);
$(".chatValue").keypress(function(e){
if(e.keyCode == 13 && $(".chatValue").val() != ""){
clearInterval(refresh);
var me = $(".me").val();
var chat = $(".chatValue").val();
var time = $(".timeChat").val();
$(".chatContainer").append(me+": "+chat+" ("+time+")"); //showing a new message before database updated
$(".chatValue").val("");
$.post("chat.php",{submitChat: true,chat: chat,time: time});
}
});
});
Upvotes: 1
Views: 134
Reputation: 943515
Presumably refreshChats
performs Ajax.
When you clear the interval, you prevent refreshChats
from running again.
If an HTTP request has already been sent, that won't prevent the event handler triggering when the HTTP response arrives, so the response will still be processed.
You need to set a flag to cancel the processing of the response (or to make the success handler abort without doing anything significant).
Upvotes: 1