Search code examples
jqueryajaxxmlhttprequestjqxhr

Why does the jquery ajax documentation mean when it says "For backward compatibility with XMLHttpRequest"


I'm looking at the documentation for the current version (1.11.2) of jQuery's ajax method. It prefaces the explanation of the jqXHR object with the following line:

For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:

Why is this "backwards compatibility"? Is XMLHttpRequest deprecated? And if so, what is the proper way to access the HTTP response if not through the jqXHR object?

Note: It seems that a lot of blog posts about .ajax() tell you to use success and error, despite that they are deprecated. Should I be doing something more like:

$.ajax( ... )
.done(function(data, textStatus, jqXHR) {
    console.log("success: " + jqXHR.responseText );
})
.fail(function(jqXHR) {
    console.log( "error: " + jqXHR.status + " (" + jqXHR.responseText + ")" );
});

Solution

  • Why is this "backwards compatibility"?

    Because a long time ago, jQuery's ajax method returned the XMLHttpRequest object directly.

    And if so, what is the proper way to access the HTTP response if not through the jqXHR object?

    Through the arguments to the callback function success and/or the promise's done.

    It seems that a lot of blog posts about .ajax() tell you to use success and error, despite that they are deprecated.

    No, they aren't. You're confusing the jqXHR.success / jqXHR.error methods with the success and error callbacks in the ajax options. The former were very temporarily in the API and are indeed deprecated; the latter have been in the API forever and are not deprecated. This is perfectly fine:

    $.ajax({
        url: "/whatever",
        success: function(data) {
            // Do something with `data`
        },
        error: function() {
            // Handle error
        },
        complete: function() {
            // Handle completion
        }
    });
    

    If you prefer, use the newer promise stuff:

    $.ajax({
        url: "/whatever"
    }).done(function(data) {
        // Do something with `data`
    }.fail(function() {
        // Handle error
    }).always(function() {
        // Handle completion
    });
    

    But the success/error/complete options are not deprecated.