jQuery $.ajax and readyStates

35,682

Solution 1

$.ajax() returns the XmlHttpRequest object, so if you really want to access it as the state changes, you can do this:

var xhr = $.ajax({ ... });
xhr.onreadystatechange = function() { alert(xhr.readyState); };

But the built-in callbacks should be all you need for most uses, particularly success and complete.

To do things before the request fires, use beforeSend, or more appropriately for most cases, the .ajaxStart() and .ajaxStop() events...for example to show a loading message whenever any ajax activity is going on.

Solution 2

Method, tested with jQuery 2.0.2:

$.ajax({
    beforeSend: function (jqXHR, settings) {
        var self = this;
        var xhr = settings.xhr;
        settings.xhr = function () {
            var output = xhr();
            output.onreadystatechange = function () {
                if (typeof(self.readyStateChanged) == "function") {
                    self.readyStateChanged(this);
                }
            };
            return output;
        };
    },
    readyStateChanged: function (xhr) {
        if (xhr.readyState == 1) {
            /* Connected! Do something */
        }
    },
    url: "..."
});

Basically, what I needed was a callback after readyState becomes 1 (Connected), which, in my case, was useful when implementing long polling "push" notifications with jQuery.

Solution 3

You should be able to get all you need by setting callbacks for the success, error, and complete options in the object you pass into the ajax() method. Take a look at the documentation:

http://api.jquery.com/jQuery.ajax/

Basically, it works like this:

$.ajax({
    url: 'ajax/test.html',
    success: function(data) {
        alert('Load was performed.');
    },
    error: function() {alert("error occurred.")},
    complete: function() {alert("ajax complete.")}
});

You can see the docs for exactly what parameters you have access to in the callback functions.

Share:
35,682
tetris
Author by

tetris

Updated on November 18, 2021

Comments

  • tetris
    tetris over 2 years

    How to call the Ajax ready states on the jQuery $.ajax method?