jqXHR object

In the previous paragraph, we saw that a jqXHR object can be used in a method callback function. In fact, all jQuery methods that are designed to send ajax requests are somehow connected with it.

This object is a wrapper around the standard javascript XMLHttpRequest object. For compatibility with XMLHttpRequest, jqXHR offers us the following properties and methods:

  • readyState: returns the state of the request. Has values ​​from 0 (request not sent) to 4 (request completed)
  • status: returns the HTTP status code it receives from the server
  • statusText: returns the status of the request as text
  • responseXML: returns the response as XML
  • responseText: returns the response in plain text
  • setRequestHeader(name, value): sets the request header name with value. If there is already a similar header, then its value is replaced by the value
  • getAllResponseHeaders(): returns all response headers
  • getResponseHeader(name): returns the response header name
  • abort(): aborts the request

But if the XMLHttpRequest object prompts us to handle the event to process the response on ready state change, then jqXHR has several methods defined at once that help process the response:

  • done(function(data, textStatus, jqXHR)): handles a successful response from the server
  • fail(function(jqXHR, textStatus, errorThrown)): handles the response from the server, the request to which ended in an error
  • always(function(data|jqXHR, textStatus, jqXHR|errorThrown)): handles both successful responses from the server and error messages
  • then(function(data, textStatus, jqXHR), function(jqXHR, textStatus, errorThrown)): enables the functionality of the done and fail methods, taking two response handling functions respectively

So, earlier we used the get method like this:

$.get('ajax.php', function(data) {
                alert('Data loaded');

But since the get method returns a jqXHR object, we can write it like this using the method done:

$.get('ajax.php').done(function(data) {
                alert('Data loaded');

Similarly, we can apply other methods:

var jqxhr=$.get('ajax.php');
jqxhr.done(function(data) {
jqxhr.fail(function(data) {