Alert on jquery ajax requst when new response
Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
-
Marius
- Posts:107
Alert on jquery ajax requst when new response
I have a jquery ajax function that is called every second, with setTimeout().
I want an alert to pop up whenever a new message is received.
Here's the ajax code to receive the message from server.
Code: Select all
$(document).ready(function ajax(){
$.ajax({
type: 'GET',
url: 'recieve.php',
dataType: 'html',
success: function(response){
$("#message").html(response);
},
complete: function(){
setTimeout(ajax,1000);
}
});
});
Where should i put
alert('New message received'); so that it only pops up only when a new message is received?
If i put alert in success function it is popping up every second.
Admin
Posts:805
Try something like this, store the previous response into a variable, and alert the message if response changed:
Code: Select all
var msg_res =''; //store the previous response
$(document).ready(function ajax(){
$.ajax({
type: 'GET',
url: 'recieve.php',
dataType: 'html',
success: function(response){
//if response changed, not the same as in msg_res
if(response != msg_res){
msg_res = response; //store new response
$("#message").html(response);
alert('New message received');
}
},
complete: function(){
setTimeout(ajax,1000);
}
});
});