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).
$.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 },
//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); });
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.