• How to cancel/abort jQuery AJAX request?

  • jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so we can use abort().
  • abort Method (MSDN)- Cancels the current HTTP request.
  • abort() (MDN) – If the request has been sent already, this method will abort the request.
jQuery Code
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()
[ad type=”banner”]

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.

  • The jquery ajax method returns a XMLHttpRequest object. we can use this object to cancel the request.
  • The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for/handle the response.
  • The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4).
jQuery Code
$(document).ready(
var xhr;

var fn = function(){
if(xhr && xhr.readyState != 4){
xhr.abort();
}

var interval = setInterval(fn, 500);
);
jQuery Code
 xhr = $.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
}
});
};

jQuery Code
$.xhrPool = [];

$.xhrPool.abortAll = function() {
/* Original example used _underscore api
_.each(this, function(jqXHR) {
jqXHR.abort();
});
*/
$.each(this, function(jqXHR) {
jqXHR.abort();
});
};

$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
}
});

jQuery Code
$.xhrPool = [];

$.xhrPool.abortAll = function() {
$.each(this, function(jqXHR) {
jqXHR.abort();
});
};

$.ajaxSetup({
beforeSend: function(jqXHR) {
$.xhrPool.push(jqXHR);
},
complete: function(jqXHR) {
var index = $.xhrPool.indexOf(jqXHR);
if (index > -1) {
$.xhrPool.splice(index, 1);
}
}
});
[ad type=”banner”]

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

  • Create a counter
  • Increment the counter when we 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:

jQuery 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");
jQuery Code
 }
});
}
sendXHR();
sendXHR();
sendXHR();
// AJAX requests complete in any order but only the last
// one will trigger "Process the response" message

Here there are three different solution approaches.

  • Cancel the request
  • Execute all request but only processes the result of the last submit
  • Prevents new requests as long as another one is still pending
jQuery Code
<!DOCTYPE html>
<html>

<head>
<title>AJAX Test</title>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
var Ajax1 = {
call: function () {
if (typeof this.xhr !== 'undefined')
this.xhr.abort();
this.xhr = $.ajax({
jQuery Code
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
jQuery Code
 }
}
});
}
};
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
},
jQuery Code
complete: function () {
self.active = false;
}
});
}
}
};
$(function () {
$('#button').click(function (e) {
Ajax3.call();
});
})
</script>
</head>

<body>

  • Here is the solution for Abort Ajax requests using jQuery:
jQuery Code
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);
});

If we check an if statement to check whether the ajax request is null or not.

  • We needed to cancel pending requests that may have taken longer than the latest/most current request.

we can use something like this:

jQuery Code
//On document ready
var ajax_inprocess = false;

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

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

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

  • 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 will trying to solve (that others may run in to as well) is that when the user entered information in an input field, we wanted to fire off a request for a Google Instant type of feel.
  • To avoid unnecessary requests and to maintain the front-end.
jQuery Code
var xhrQueue = [];
var xhrCount = 0;

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

xhrQueue.push(xhrCount);

setTimeout(function(){

xhrCount = ++xhrCount;
jQuery Code
if (xhrCount === xhrQueue.length) {
// Fire Your XHR //
}

}, 150);

});

This will essentially send one request every 150ms (a variable that we can customize for our own needs).

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

example:

jQuery Code
//jQuery ajax
$(document).ready(
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);
[ad type=”banner”]

  • The below example demonstrates how to cancel an AJAX request– if data is not returned from the server within a predefined wait time.

HTML :

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

JS CODE:

jQuery Code
var isDataReceived= false, waitTime= 1000; 
$(function() {
// Ajax request sent.
var xhr= $.ajax({
url: 'http://api.joind.in/v2.1/talks/10889',
jQuery Code
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);
});

Categorized in: