How to Abort jQuery Ajax Requests


Hi everyone,

It's been long time since the last time and I decided to post a useful content :  "How to abort and track the status of jQuery Ajax requests."

First we all should know the return types of jQuery ajax methods, so lets walk thru their return types :


jQuery.ajax( options )Returns: XMLHttpRequest
Load a remote page using an HTTP request.
load( url, datacallback )Returns: jQuery
Load HTML from a remote file and inject it into the DOM.
jQuery.get( url, datacallbacktype )Returns: XMLHttpRequest
Load a remote page using an HTTP GET request.
jQuery.getJSON( url, datacallback )Returns: XMLHttpRequest
Load JSON data using an HTTP GET request.
jQuery.getScript( url, callback )Returns: XMLHttpRequest
Loads and executes a JavaScript file using an HTTP GET request.
jQuery.post( url, datacallbacktype )Returns: XMLHttpRequest
Load a remote page using an HTTP POST request.


As long as they return XMLHttpRequest we can use methods peculiar to XMLHttpRequest. You can find the complete reference of XMLHttpRequest here

And this is code how to handle status changes :
function() {
    var _resultText = $("#r_ResultText");

    _loading.show();
    _resultText.hide();

    var _ajaxRequest = $.getJSON("login.aspx?callback=SendPassword");

// this is the code which handles status 
    _ajaxRequest.onreadystatechange = function() {
    if (_ajaxRequest.status == 408) { //time out code
        _loading.hide();
        _resultText.show().html("Result:
" + "Time-Out, please try again in a few minutes");
         }

    }

0 comments: