Getting Started With jQuery - Advanced Ajax jqXHR and Events
Written by Ian Elliot   
Monday, 18 January 2016
Article Index
Getting Started With jQuery - Advanced Ajax jqXHR and Events
Applications of beforeSend

The jQuery approach to Ajax is built on the jqXHR object which wraps the XmlHttpRequest object that the browser provides. It isn't often that you need delve this deeply into jQuery Ajax, but when you do nothing else will do. 

Just jQuery
Events, Async & AJAX

Is now available as a print book: Amazon 

jquery2cover

 

Contents

  1. Events, Async & Ajax (Book Only)
  2. Reinventing Events
  3. Working With Events
  4. Asynchronous Code
  5. Consuming Promises
  6. Using Promises 
  7. WebWorkers
  8. Ajax the Basics - get
  9. Ajax the Basics -  post
  10. Ajax - Advanced Ajax To The Server
  11. Ajax - Advanced Ajax To The Client
  12. Ajax - Advanced Ajax Transports And JSONP
  13. Ajax - Advanced Ajax The jsXHR Object
  14. Ajax - Advanced Ajax Character Coding And Encoding 

Also Available:

buy from Amazon

smallcoverjQuery

 

Advanced Attributes

The jqXHR Object

The jqXHR object, or jq(uery)XmlHttpRequest object, is one of the low level features of using jQuery Ajax that at first can mostly be ignored. However, it keeps popping up as it is passed in as a parameter to most of the Ajax event handlers and Promise methods. When you first start using jQuery Ajax you can just treat it as an object that has a number of useful properties that tell you about the nature of the request.

In fact, the jqXHR object is a wrapper for the native XMLHttpRequest object that the browser creates to make an Ajax request.  It isn't just a wrapper it extends the native object where necessary and stands in for it when a transport is used that isn't based on the XMLHttpRequest object.

This is an important point because Ajax proper is based on the XMLHttpRequest object that the browser provides and this implements the HTTP transport needed between the client and the server. However as we saw in the previous chapter jQuery can make use of other more general transport objects which are not strictly Ajax and certainly don't make use of the browsers XMLHttpRequest object. In this case the transport has to create a jqXHR object that provides as many properties and methods as possible. 

In addition to wrapping the XMLHttpRequest object the jqXHR object is also a Promise which means it can be used to handle asynchronous requests more logically.

An older set of methods - success, error and complete are still supported but don't use them as they are being deprecated - see later for more details.

The jqXHR object also provides the following properties and methods: 

  • readyState

    0 UNSENT The connection has not started
    1 OPENED The data is sent
    2 HEADERS_RECEIVED headers and status are available.
    3 LOADING Downloading; responseText holds partial data.
    4 DONE The operation is complete.

     

  • status
    The HTTP result code.

  • statusText
    The HTTP result text.

  • responseXML and/or responseText when the underlying request responded with xml and/or text, respectively

  • setRequestHeader(name, value) 
    replaces the named header with the value given. This can only be used from the beforeSend function - see later.

  • getAllResponseHeaders()
    Returns a single string with all of the headers

  • overrideMimeType()
    overrides the mimetype header. This can only be used in the beforeSend function.
  • getResponseHeader(name)
    returns a string with the named header

  • statusCode()
    This can be used to set callbacks for any HTTP result code. It has to be set in the beforeSend function - see later.

  • abort()
    Aborts the transfer - if this is possible. 

If you look at the specification of the native XMLHttpRequest object you will discover that it has many more advanced options. However these are not supported by the jsXHR object because they do not work on all browsers. The list of properties and methods is likely to expand as the newer features spread to the majority of browsers. 

However if you want to try to set a field on the native XMLHttpRequest you can use the xhrFields option. 

xhrField=object of key value pairs

sets the fields named as keys in the object to the value specified. 

For example

options.xhrFields={"timeout",1000);

sets the timeout field to 1000 ms. In most cases you should use the option provided by jQuery rather than setting the native field but this is useful if you need to modify any non-standard fields.

If you really want to do advanced things you can even make use of the xhr option to provide a function that will create a custom XMLHttpRequest object.

xhr=function()

Set to a function that returns a custom XMLHttpRequest object. 

In most cases this is only useful in creating an enhanced native XMLHttpRequest object.

 

One of the confusing aspects of the jsXHR object is that many of its properties and methods are available as options in the main Ajax function call.

In most cases which you use is a matter of convenience and preference and, most importantly, exactly where in the Ajax request the actions are carried out. Setting jsXHR properties and using its methods generally happens at a later stage in the request and therefore tends to override what has been set using the Ajax request options.

 

AjaxSetup

As well as being able to set options when you make an Ajax call you can also pre-specify all of the options as defaults using the AjaxSetup method. 

For example:

$.ajaxSetup({ url:"mysite.com"})

sets the default for the url property to mysite.com. Now if an Ajax call, any Ajax call, is started without an explicit url option it will request data from mysite.com. 

That is you can set defaults for all Ajax options which apply to all Ajax methods - ajax, get, post etc. - unless they are overridden by explicit option values.

The jQuery documentation argues that this isn't a good idea because it might change the way that Ajax requests are handled from third party plugins and so on but sometimes this is what you want to do. So rather then avoiding the use of ajaxSetup you should consider very carefully how to use it. Always specify every option that your Ajax call relies on and don't simply accept defaults that you might later change. 

Normally any defaults you set using ajaxSetup can be overridden by explicitly set options at the time of the call - however using beforeSend and the jsXHR object you can enforce many of the defaults - as explained in the next section

beforeSend

beforeSend=function(jsXHR,options)

Called just before the Ajax transport is started so that you can modify any aspect of the request.

You can change the properties of the jsXHR object any time you have access to it but often you need to add code to the beforeSend function to modify it just before the Ajax request gets underway i.e. when jsXHR.readyState==0. 

Notice that at this early stage many of the properties and methods that use data set by the response are either null or undefined. For example, if you try to access say status or statusText you will find they are undefined. 

One reason for using the beforeSend function it to modify options and jsXHR properties after they have been set by the Ajax call. For example:

options.beforeSend=function(jqXHR,options){
 options.url="process.php";
};

sets the url property to "process.php" no matter what the Ajax request originally asked for. 

Using the beforeSend function you can override any choices made at the Ajax call by setting them later in the request sequence. By setting beforeSend in ajaxSetup you can enforce your choices for all Ajax requests without having to set it as part of the options in each Ajax call: 

$.ajaxSetup({
  beforeSend:function(jqXHR,options){
                        options.url="process.php";
             }
}

The beforeSend approach has a number of common applications which we'll now explore.



Last Updated ( Thursday, 05 May 2022 )