Page 1 of 1

Alert on jquery ajax requst when new response

Posted: 03 Jun 2017, 06:44
by Marius
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.

Alert on jquery ajax requst when new response

Posted: 03 Jun 2017, 06:48
by Admin
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);
   }
  }); 
});