What is the jqXHR object?

Sam Deering
Share

The jQuery.ajax() function is basically just one big jqXHR object (essentially a fake javaScript xhr object).

  • The jqXHR (jQuery XMLHttpRequest) replaces the browser native XMLHttpRequest object.
  • jQuery wraps the browser native XMLHttpRequest object with a superset API.
  • The jQuery XMLHttpRequest (jqXHR) object is returned by the $.ajax() function.
  • The jqXHR object simulates native XHR functionality where possible.

So what does it do? …

  • It handles the HTTP request headers (Last-Modified, etag, Content-Type, MIME types etc…).
  • It handles the callbacks of the request (including promise callbacks .done(), .fail() etc…)
  • It handles any prefilters set for the request.
  • It handles any timeouts set for the request.
  • It handles any cross domain calls (including jsonp).

In the jQuery source code it is even commented as Fake xhr

// Fake xhr
jqXHR = {

  ...

}

jqZHR implements a Promise Interface

The jqXHR objects returned by $.ajax() implement the Promise interface. The object has all the properties, methods, and behavior of a Promise. Read more on deferred.promise().

jqXHR Backward Compatibility with XMLHttpRequest

For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods: readyState, status, statusText, responseXML and/or responseText (with xml and/or text response, respectively), getAllResponseHeaders(), getResponseHeader(), abort() and setRequestHeader(). Since success, error, complete and statusCode cover all the requirements, jqXHR doesn’t provide any support for onreadystatechange.

// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;

Background info on XHR request

XMLHttpRequest (XHR) is an API available in web browser scripting languages such as JavaScript. It is used to send HTTP or HTTPS requests directly to a web server and load the server response data directly back into the script.

  • XMLHttpRequest is a JavaScript object that was designed by Microsoft and adopted by Mozilla, Apple, and Google.
  • Despite its name, XMLHttpRequest can be used to retrieve any type of data, not just XML, and it supports protocols other than HTTP (including file and ftp).
  • XMLHttpRequest is subject to the browser’s same origin policy in that, for security reasons, requests will only succeed if they are made to the same server that served the original web page.
  • The concept behind the XMLHttpRequest object was originally created by the developers of Outlook Web Access (by Microsoft) for Microsoft Exchange Server 2000.

Further Reading