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).
$.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);}});
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;functionsendXHR(){// sequence number for the current invocation of functionvar seqNumber =++xhrCount;
$.post("/echo/json/",{delay: Math.floor(Math.random()*5)},function(){// this works because of the way closures workif(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
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 POSTurl:"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 readyvar 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 functionif(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.
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.