1

I want cancel jquery $.ajax call request with datatype json on window unload event. I tried doing this and it is throwing error on xhr.abort(); line.

var xhr = $.ajax({         
    type: "POST",
    url: serviceUrl,
    dataType: "text json",
    data: ajaxParameters,
    async: true,
    contentType: "application/json; charset=utf-8",
    error: function(request, status, error) {
    },
    complete: function(e, xhr, settings) {                      
    }
});

$(window).onunload = function(){
    xhr.abort();
}
AshokD
  • 442
  • 4
  • 14
  • 2
    Your code has a syntax error (missing comma after `serviceUrl`). Also, it should be `$(window).on('beforeunload' ...)` – Explosion Pills Jan 29 '13 at 06:14
  • 2
    What's the error being thrown? – Ja͢ck Jan 29 '13 at 06:15
  • 1
    @AshokD Just curious, why would someone want to abort the request on window close? Won't it be automatically aborted? – Salman Jan 29 '13 at 06:18
  • @Салман not generally, no – Explosion Pills Jan 29 '13 at 06:20
  • @ExplosionPills didn't get you, what do you mean? aborting means we don't want response, and if we closing the browser, we anyways don't receive response. – Salman Jan 29 '13 at 06:23
  • @Салман but it doesn't halt the request on the server side – Explosion Pills Jan 29 '13 at 06:25
  • Possible duplicate http://stackoverflow.com/q/600494/1618713 – Faisal Sayed Jan 29 '13 at 06:25
  • just a side note to handle ajax requests I use ajaxQueue https://github.com/gnarf37/jquery-ajaxQueue , it has better way to manage requests in case you are sending lots of ajax requests to server and wants to avoid deadlock at serverside (specially session) – sakhunzai Jan 29 '13 at 07:02
  • Here scenario is service call is made and IIS is processing it, between this client page is unloaded, now server sends the response and waits for client to send acknowledgement(Page is already unloaded so nobody is available to receive response). Because of this there are requests which are getting too much time in IIS logs, to avoid this I'm want the abort the ajax call – AshokD Jan 30 '13 at 03:42

1 Answers1

0

Try this out...

// Global variable
var xhr;

xhr = $.ajax({         
    type: "POST",
    url: serviceUrl,
    dataType: "text json",
    data: ajaxParameters,
    async: true,
    contentType: "application/json; charset=utf-8",
    error: function(request, status, error) {
    },
    complete: function(e, xhr, settings) {                      
    }
});

$('body').on('beforeunload',function(){
    xhr.abort();
}
ATOzTOA
  • 34,814
  • 22
  • 96
  • 117