szpal szpal - 6 months ago 113
Ajax Question

jQuery Ajax stop long polling

I wrote a ping html version, which is appears in a jQuery dialog box.

I wish that when I close the dialog box, then stop the ping.

But in my version alert the 'close' message, and again continues the ping.

<script type="text/javascript">
var init = 1;
var timestamp = null;
var tag = $("<div></div>");
function waitForMsg() {
$.ajax({
type: "GET",
url: "/modules/ping2.php?host=localhost&tsp="+timestamp+"&init="+init,
cache: false,
success: function(data) {
var json = eval('('+data+ ')');
var str = json['out'].replace(/\n/g, "<br>");
tag.html(str).dialog({
title: 'Ping',
modal: false,
width: 480,
height: 550,
close: function() {
alert('close');
}
}).dialog('open');
timestamp = json["tsp"];
init = 0;
setTimeout("waitForMsg()", 1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error: "+textStatus + " "+ errorThrown);
setTimeout("waitForMsg()", 15000);
}
});
}
$(function() {
$("#button").on('click', function() {
waitForMsg();
});
});
</script>


How do i cancel the polling?

Answer

as i pointed out in my comment :

<script type="text/javascript">
  var timeout; // this is a variable the timout will be assigned to
  var init = 1;
  var timestamp = null;
  var tag = $("<div></div>");
  function waitForMsg() {
    $.ajax({
      type: "GET",
      url: "/modules/ping2.php?host=localhost&tsp="+timestamp+"&init="+init,
      cache: false,
      success: function(data) {
        var json = eval('('+data+ ')');
        var str = json['out'].replace(/\n/g, "<br>");
        tag.html(str).dialog({
          title: 'Ping',
          modal: false,
          width: 480,
          height: 550,
          close: function() {
            alert('close');
            clearTimeout(timeout); // here we clear the timeout
          }
        }).dialog('open');
        timestamp = json["tsp"];
        init = 0;
        timeout = setTimeout("waitForMsg()", 1000); // here we assign the timout
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("error: "+textStatus + " "+ errorThrown);
        setTimeout("waitForMsg()", 15000);
      }
    });
  }
  $(function() {
    $("#button").on('click', function() {
      waitForMsg();
    });
  });
</script>
Comments