3

I'd like cancel if my ajax request is taking long time with slower connections.

I show an overlay when .ajaxStart() and if takes longer than five secons (i managed with setInterval) a button appears on overlay that should cancel the current ajax request.

heres some of my code:

jqXHR = $.ajax({
    url: 'includes/inc_ajax.php',
    type: 'POST',
    data: '&ajax=1&action=7',
    success: function (txt) {
        var cntr = $.parseJSON(txt);
        $("#onlineppl").html(cntr.online);
        $("#todayppl").html(cntr.bugun);
        $("#totalppl").html(cntr.toplam);
    }
});

$("#abortAjax").button({ icons: {secondary: "ui-icon-cancel"} }).click(function() {
    $(jqXHR).abort();
});

Do I have to assign the $.ajax() function to a variable to abort it? I have many ajax request called by ajax too so i guess the browser can't track the same var name that causes the abort method not to work.

This is my first question here and I am a bit confused. Any help appreciated. Thanks.

Algün
  • 35
  • 1
  • 1
  • 3

3 Answers3

4

Well, you culd try:

jqXHR.abort();

Whitout the $()

Note its not tested, i saw it somewhere

EDIT

Aah found it:

Stop all active ajax requests in jQuery

Community
  • 1
  • 1
Limpan
  • 662
  • 1
  • 5
  • 6
0

Yes, JavaScript is a prototype-based language and every object instance has a pointer. When two ajax calls start, your jqXHR only returns the pointer to the second ajax call. This is also indicated in this article where you have to get a token back from a function, so that you can refer to it to cancel it later.

Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188
-1

Note - you can't really stop an AJAX request from processing on the server once it has been received. The server will continue processing the request even though the browser is no longer listening for a response. There is no reliable way to make the web server stop in its tracks with processing a request that is in progress, except for implementing something manually (like a session property check that gets set by a different page).

So basically the server will still run, but the client browser will ignore the response - be aware that this also counts in your connections limitations to a domain (which is usually only TWO by default).

Leon
  • 4,532
  • 1
  • 19
  • 24
  • 1
    to whoever gave the -1 -> at the time I answered (2011) there was NO WAY to abort the Ajax call on the server-side! The accepted answer only aborts the client call, but will NOT STOP the processing on the server... – Leon Jan 21 '20 at 20:44
  • 1
    Technically, he was asking about cancelling the ajax request not the server processing on the server. Your answer was answering a totally different question. It was wrong 9 years ago, still wrong now. I'm narrowing my eyes filled with judgement as I type this and I'm clicking the [ Add Comment ] button with a mercilessly stoic expression. ... *click* – Aries Mar 20 '20 at 07:35