Just starting out in web programming and currently delving into javascript and jquery ajax..
This snippet represents my javascript code. The refresh variable controls an interval for updating the chat by fetching chats from the database and displaying them in the chat container every 2 seconds. My goal is to stop this interval, append a new message to the container, then resume the interval after submitting the message.
The issue arises when I hit enter to submit the message - the new chat appears momentarily in the container but gets replaced as the container refreshes with records from the database (the clearInterval function doesn't seem to work yet). Interestingly, it only stops the interval once the function has completed. Why? Oh 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});
}
});
});