By lukewm


2009-01-15 12:45:18 8 Comments

Using jQuery, how can I cancel/abort an Ajax request that I have not yet received the response from?

18 comments

@meouw 2009-01-15 12:56:49

Most of the jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so you can just use abort().

See the documentation:

  • abort Method (MSDN). Cancels the current HTTP request.
  • abort() (MDN). If the request has been sent already, this method will abort the request.
var xhr = $.ajax({
    type: "POST",
    url: "some.php",
    data: "name=John&location=Boston",
    success: function(msg){
       alert( "Data Saved: " + msg );
    }
});

//kill the request
xhr.abort()

UPDATE: As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR. This object appears to expose all of the native properties and methods so the above example still works. See The jqXHR Object (jQuery API documentation).

UPDATE 2: As of jQuery 3, the ajax method now returns a promise with extra methods (like abort), so the above code still works, though the object being returned is not an xhr any more. See the 3.0 blog here.

UPDATE 3: xhr.abort() still works on jQuery 3.x. Don't assume the update 2 is correct. More info on jQuery Github repository.

@Yuval Adam 2009-01-15 13:04:40

Can you please elaborate on what abort() exactly does?

@James 2009-01-15 13:15:35

@meouw 2009-01-15 13:19:49

It's like clicking the 'stop' button on your browser. It cancels the request. You can then reuse the same XHR object for another request.

@pepkin88 2011-03-12 12:31:19

@brad Unfortunately, abort doesn't close an established connection with the server, so success will be still called. This is very problematic for implementations of Comet with long polling.

@Asad Saeeduddin 2012-12-09 06:37:44

@ErvWalter You could dispatch another request that cancels the previous one.

@user420667 2012-12-29 17:27:40

@JoeCoderGuy: I'm not convinced. The server will still do it's thing, but in my tests (in Chrome v23 at least), the javascript success method is not called.

@user1382306 2012-12-29 19:44:46

@user420667 I must have a weird version because it doesn't cancel mine (same ver). I did see on another question that doing it on localhost may not give enough time to cancel stackoverflow.com/questions/8584402/…

@BJ Safdie 2013-11-08 02:23:41

In my tests, the request is aborted at the browser, but the .fail() method is invoked with a jqXHR,status = 0, and jqXHR,statusMessage = "abort"

@Funkodebat 2014-05-08 18:24:44

for nodejs, call req.on('close', function() { }) to detect if the javascript side has called .abort()

@shasi kanth 2014-07-14 09:11:41

In some cases, i observed that pressing and holding the escape button cancels the AJAX requests.

@jcubic 2016-01-31 13:05:32

It will no longer work for jQuery 3.0 blog.jquery.com/2016/01/14/jquery-3-0-beta-released

@Umair Khan 2016-04-05 15:08:13

you can use return false if specific condition meet

@anson 2017-05-18 19:34:17

Since this is such a high rep answer, it really should be reflected in it that this no longer works (as @jcubic mentioned)

@alarive 2017-10-11 10:00:00

.abort() still works for me in jQuery 3.2.1. This comment in a related github issue by a jQuery core team member seems to imply that this answer is incorrect and that .abort() was not removed.

@cuixiping 2015-05-28 09:17:53

Just call xhr.abort() whether it's jquery ajax object or native XMLHTTPRequest object.

example:

//jQuery ajax
$(document).ready(function(){
    var xhr = $.get('/server');
    setTimeout(function(){xhr.abort();}, 2000);
});

//native XMLHTTPRequest
var xhr = new XMLHttpRequest();
xhr.open('GET','/server',true);
xhr.send();
setTimeout(function(){xhr.abort();}, 2000);

@Soubhagya Kumar 2018-05-18 13:17:35

You can abort any continuous ajax call by using this

<input id="searchbox" name="searchbox" type="text" />

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

<script type="text/javascript">
     var request = null;
        $('#searchbox').keyup(function () {
            var id = $(this).val();
            request = $.ajax({
                type: "POST", //TODO: Must be changed to POST
                url: "index.php",
                data: {'id':id},
                success: function () {

                },
                beforeSend: function () {
                    if (request !== null) {
                        request.abort();
                    }
                }
            });
        });

</script>

@zloctb 2016-01-04 13:35:37

The following code shows initiating as well as aborting an Ajax request:

function libAjax(){
  var req;
  function start(){

  req =    $.ajax({
              url: '1.php',
              success: function(data){
                console.log(data)
              }
            });

  }

  function stop(){
    req.abort();
  }

  return {start:start,stop:stop}
}

var obj = libAjax();

 $(".go").click(function(){


  obj.start();


 })



 $(".stop").click(function(){

  obj.stop();


 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="go" value="GO!" >
   <input type="button" class="stop" value="STOP!" >

@SnareChops 2016-01-29 00:48:14

Please provide an explanation of how this solves the question. This will help the OP and other future searchers.

@oyophant 2013-03-06 14:29:03

We just had to work around this problem and tested three different approaches.

  1. does cancel the request as suggested by @meouw
  2. execute all request but only processes the result of the last submit
  3. prevents new requests as long as another one is still pending

var Ajax1 = {
  call: function() {
    if (typeof this.xhr !== 'undefined')
      this.xhr.abort();
    this.xhr = $.ajax({
      url: 'your/long/running/request/path',
      type: 'GET',
      success: function(data) {
        //process response
      }
    });
  }
};
var Ajax2 = {
  counter: 0,
  call: function() {
    var self = this,
      seq = ++this.counter;
    $.ajax({
      url: 'your/long/running/request/path',
      type: 'GET',
      success: function(data) {
        if (seq === self.counter) {
          //process response
        }
      }
    });
  }
};
var Ajax3 = {
  active: false,
  call: function() {
    if (this.active === false) {
      this.active = true;
      var self = this;
      $.ajax({
        url: 'your/long/running/request/path',
        type: 'GET',
        success: function(data) {
          //process response
        },
        complete: function() {
          self.active = false;
        }
      });
    }
  }
};
$(function() {
  $('#button').click(function(e) {
    Ajax3.call();
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="button" type="button" value="click" />

In our case we decided to use approach #3 as it produces less load for the server. But I am not 100% sure if jQuery guarantees the call of the .complete()-method, this could produce a deadlock situation. In our tests we could not reproduce such a situation.

@vikyd 2016-10-23 11:56:31

If xhr.abort(); causes page reload,

Then you can set onreadystatechange before abort to prevent:

// ↓ prevent page reload by abort()
xhr.onreadystatechange = null;
// ↓ may cause page reload
xhr.abort();

@ganesh 2016-02-12 05:25:10

I have shared a demo that demonstrates how to cancel an AJAX request-- if data is not returned from the server within a predefined wait time.

HTML :

<div id="info"></div>

JS CODE:

var isDataReceived= false, waitTime= 1000; 
$(function() {
    // Ajax request sent.
     var xhr= $.ajax({
      url: 'http://api.joind.in/v2.1/talks/10889',
      data: {
         format: 'json'
      },     
      dataType: 'jsonp',
      success: function(data) {      
        isDataReceived= true;
        $('#info').text(data.talks[0].talk_title);        
      },
      type: 'GET'
   });
   // Cancel ajax request if data is not loaded within 1sec.
   setTimeout(function(){
     if(!isDataReceived)
     xhr.abort();     
   },waitTime);   
});

@Bram Vanroy 2016-07-06 19:54:02

$.ajax provides a timeout option so you don't need to write your own. Simply use ..., data: {...}, timeout: waitTime,....

@ganesh 2018-02-15 05:17:34

@Bram - Thanks for sharing. I didn't know that.

@comeGetSome 2015-06-17 18:44:24

there is no reliable way to do it, and I would not even try it, once the request is on the go; the only way to react reasonably is to ignore the response.

in most cases, it may happen in situations like: a user clicks too often on a button triggering many consecutive XHR, here you have many options, either block the button till XHR is returned, or dont even trigger new XHR while another is running hinting the user to lean back - or discard any pending XHR response but the recent.

@Salman A 2014-01-18 12:55:07

AJAX requests may not complete in the order they were started. Instead of aborting, you can choose to ignore all AJAX responses except for the most recent one:

  • Create a counter
  • Increment the counter when you initiate AJAX request
  • Use the current value of counter to "stamp" the request
  • In the success callback compare the stamp with the counter to check if it was the most recent request

Rough outline of code:

var xhrCount = 0;
function sendXHR() {
    // sequence number for the current invocation of function
    var seqNumber = ++xhrCount;
    $.post("/echo/json/", { delay: Math.floor(Math.random() * 5) }, function() {
        // this works because of the way closures work
        if (seqNumber === xhrCount) {
            console.log("Process the response");
        } else {
            console.log("Ignore the response");
        }
    });
}
sendXHR();
sendXHR();
sendXHR();
// AJAX requests complete in any order but only the last 
// one will trigger "Process the response" message

Demo on jsFiddle

@Tharindu Kumara 2014-10-15 09:14:27

It is always best practice to do something like this.

var $request;
if ($request != null){ 
    $request.abort();
    $request = null;
}

$request = $.ajax({
    type : "POST", //TODO: Must be changed to POST
    url : "yourfile.php",
    data : "data"
    }).done(function(msg) {
        alert(msg);
    });

But it is much better if you check an if statement to check whether the ajax request is null or not.

@Zesty 2015-07-29 05:02:27

I also check if a request is already running, but I use a boolean, as it's lighter.

@brianrhea 2014-02-03 18:43:27

As many people on the thread have noted, just because the request is aborted on the client-side, the server will still process the request. This creates unnecessary load on the server because it's doing work that we've quit listening to on the front-end.

The problem I was trying to solve (that others may run in to as well) is that when the user entered information in an input field, I wanted to fire off a request for a Google Instant type of feel.

To avoid firing unnecessary requests and to maintain the snappiness of the front-end, I did the following:

var xhrQueue = [];
var xhrCount = 0;

$('#search_q').keyup(function(){

    xhrQueue.push(xhrCount);

    setTimeout(function(){

        xhrCount = ++xhrCount;

        if (xhrCount === xhrQueue.length) {
            // Fire Your XHR //
        }

    }, 150);

});

This will essentially send one request every 150ms (a variable that you can customize for your own needs). If you're having trouble understanding what exactly is happening here, log xhrCount and xhrQueue to the console just before the if block.

@Billy 2013-12-04 14:43:33

I was doing a live search solution and needed to cancel pending requests that may have taken longer than the latest/most current request.

In my case I used something like this:

//On document ready
var ajax_inprocess = false;

$(document).ajaxStart(function() {
ajax_inprocess = true;
});

$(document).ajaxStop(function() {
ajax_inprocess = false;
});

//Snippet from live search function
if (ajax_inprocess == true)
{
    request.abort();
}
//Call for new request 

@Joecoder001 2013-11-08 08:07:21

Just use ajax.abort() for example you could abort any pending ajax request before sending another one like this

//check for existing ajax request
if(ajax){ 
 ajax.abort();
 }
//then you make another ajax request
$.ajax(
 //your code here
  );

@Tei 2012-03-28 11:34:27

Save the calls you make in an array, then call xhr.abort() on each.

HUGE CAVEAT: You can abort a request, but that's only the client side. The server side could still be processing the request. If you are using something like PHP or ASP with session data, the session data is locked until the ajax has finished. So, to allow the user to continue browsing the website, you have to call session_write_close(). This saves the session and unlocks it so that other pages waiting to continue will proceed. Without this, several pages can be waiting for the lock to be removed.

@Marcus 2013-07-25 12:44:11

I had the problem of polling and once the page was closed the poll continued so in my cause a user would miss an update as a mysql value was being set for the next 50 seconds after page closing, even though I killed the ajax request, I figured away around, using $_SESSION to set a var won't update in the poll its self until its ended and a new one has started, so what I did was set a value in my database as 0 = offpage , while I'm polling I query that row and return false; when it's 0 as querying in polling will get you current values obviously...

I hope this helped

@Prestaul 2009-01-15 15:45:50

meouw's solution is correct, but if you're are interested in more control then you could try the Ajax Manager plugin for jQuery.

@brasofilo 2018-06-11 11:55:37

Link is dead and the Web Archive snapshots are 301 pages... I found a fork that looks like it's the plugin mentioned: github.com/aFarkas/Ajaxmanager/blob/master/…

@tvanfosson 2009-01-15 12:55:31

You can't recall the request but you can set a timeout value after which the response will be ignored. See this page for jquery AJAX options. I believe that your error callback will be called if the timeout period is exceeded. There is already a default timeout on every AJAX request.

You can also use the abort() method on the request object but, while it will cause the client to stop listening for the event, it may probably will not stop the server from processing it.

@Yuval Adam 2009-01-15 12:56:22

It's an asynchronous request, meaning once it's sent it's out there.

In case your server is starting a very expensive operation due to the AJAX request, the best you can do is open your server to listen for cancel requests, and send a separate AJAX request notifying the server to stop whatever it's doing.

Otherwise, simply ignore the AJAX response.

@ElephantHunter 2012-04-10 19:12:41

In this context, asynchronous simply means the request doesn't interrupt the flow of the script. Browsers now have the ability to abort the request prematurely before the request is completed.

@Lucky Soni 2014-06-28 22:18:58

How can we send a cancel request to the server? I don't understand how the server will know which request to stop processing? Could you give an example? Thank you.

@Kloar 2014-08-11 13:28:23

@LuckySoni, Elephanthunter is only discussing client-side. The server will not be affected by an .abort request

@white 2014-09-20 09:17:47

@Kloar, if the request is not yet recieved by server (f.ex. large multpart requests), client may close the socket, and the server will be affected.

@hanshenrik 2015-03-01 19:58:39

PHP check for aborted requests automatically, and terminates automatically too. see php.net/manual/en/function.ignore-user-abort.php

@Kishor Pawar 2016-06-01 10:05:22

@ElephantHunter : can you provide some reading material on browser aborting request prematurely?

@Viktor Koncsek 2017-07-12 11:36:43

@hanshenrik Thats only half true, read the docs before posting it. It only works in CLI, which is not widely used, especially not for ajax.

@hanshenrik 2017-07-12 20:33:14

@ViktorKoncsek nope, ignore_user_abort() is for web requests too (like php+Apache)

Related Questions

Sponsored Content

31 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

31 Answered Questions

[SOLVED] How to manage a redirect request after a jQuery Ajax call

18 Answered Questions

[SOLVED] How can I refresh a page with jQuery?

30 Answered Questions

49 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

6 Answered Questions

[SOLVED] Why does Google prepend while(1); to their JSON responses?

13 Answered Questions

35 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 665792 View
  • 2309 Score
  • 35 Answer
  • Tags:   javascript jquery

59 Answered Questions

[SOLVED] How do I redirect to another webpage?

15 Answered Questions

[SOLVED] "Thinking in AngularJS" if I have a jQuery background?

Sponsored Content