tags:

views:

355

answers:

3

I have a jQuery dialog box that opens and then an AJAX call is made. I would like to make it so that if the dialog box is closed or the cancel button is pressed the AJAX call is canceled and its callback function is not called. I can think of some ways to do it with a variable like so:

  function doStuff(){
    var doCallback = true;
    $('#dialog').dialog({
      title: 'Dialog Title',
      modal: true,
      buttons: {
        Cancel: function() {
          doCallback = false;
          doSomethingElse();
        }
      }
    });
    $.get('url/url/url', function(data){
      if(doCallback){
        doTheSuccessThing(data);
      }
    });
  }

But, somehow that feels dirty to me and it doesn't actually stop the AJAX call from completing. Is there a built-in way to cancel an AJAX call in progress?

+2  A: 

It appears so, though I've never done it.

$.get returns an XmlHttpRequest object, which has an abort() method you can call. Maybe try that?

inkedmn
+2  A: 

No method in jQuery, but you can just use XmlHttpRequest object returned from the jQuery get/post/ajax functions.

From the jQuery blog:

// Perform a simple Ajax request
  var req = $.ajax({
  type: "GET",
  url: "/user/list/",
  success: function(data) {
  // Do something with the data...
  // Then remove the request.
  req = null;
  }
});

// Wait for 5 seconds
setTimeout(function(){
// If the request is still running, abort it.
if ( req ) req.abort();
}, 5000);
Technowise
+2  A: 

Ok, so based off of the suggestion to use the XmlHttpRequest object returned by the $.get function I came up with this:

function doStuff(){
    var ajaxRequest = $.ajax({
                        url : 'url/url/url',
                        type : "GET",
                        success : function(data){
                          doSuccessStuff(data);
                        }
                      });

    $('#dialog').dialog({
      title: 'Stuff Dialog',
      bgiframe: true,
      modal: true,
      buttons: {
        Cancel: function() {
          ajaxRequest.abort();
          doCancelStuff();
        }
      }
    });
  }

It seems to work and feels cleaner to me.

Hector Scout
don't forget to check for ajaxRequest being null. you should reset it also in the 'success' method - then you can judge if there is an active ajax request or not
Simon_Weaver