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

Custom Headers

Typical uses of beforeSend are to set any request headers you might need. For example:

options.beforeSend=function(jqXHR,settings){
 jqXHR.setRequestHeader('myHeader', 'myValue');
};

If you examine the headers at the server - try: 

$headers = getallheaders();
foreach($headers as $key=>$val){
 echo $key . ': ' . $val . '<br>';
}

you will find that there is a new header:

myHeader: myValue

You can also specify a header or set of headers using the options. It can be done in the headers option. for example

options.headers={'myHeader','myValue'};

sets the same custom header.

The only differnce between the two methods is perhaps visibility to the programmer working at a higher level. If you use the beforeSend function then the setting of the header is slightly less visible than the options method. It also overrides any header set in the options. 

There are lot of reasons for setting custom headers. One major reason is to perform cross domain requests using CORS. As this involves the server to a great extent it is beyond the scope of this chapter -

email me if you would like to see an article that deals with using jQuery to implement CORS. 

Another common use of custom headers is to send a user name and password as part of HTTP authentication. To make things easier in this case jQuery provides the username and password options which can be set to the appropriate user name and password and automatically generated the necessary authentication headers. 

Setting HTTP code handlers.

There is a facility in jQuery to define handlers that are automatically called according to the HTTP code returned by the server. You can, of course use the jsXHR status property and an if statement within the done or fail methods to explicitly call status code handlers but if you register a status code handler using the statusCode function it will be called automatically. 

For example,

options.beforeSend=function(jqXHR,settings){
 jqXHR.statusCode({404:
   function(data, textStatus, jqXHR){
     console.log("status 404");
     console.log(textStatus);
   }
  });
}

This passed to the statusCode function a map of key value pairs. In this case the value is the HTTP code and the value is the function to be called when that HTTP code is returned. 

You can achieve exactly the same result using the statusCode option:

options.statusCode={404:
   function(data, textStatus, jqXHR){
     console.log("status 404");
     console.log(textStatus);
   }
 }

Again which one is best to use depends on at what point in the request you want to attach the handlers. 

The Local and Global Event Handlers

In most cases you only need to make use of the Promise that the ajax method returns to handle the result of an Ajax request. However before the use of the Promise object there were and still are the old event handlers.

These are deprecated and you shouldn't use them if at all possible but you might need to know about them:

  • success is the same as the Promise done method
  • error is the same as the Promise fail method
  • complete is the same  as the Promise always method 

The call sequence of all of the event handlers is:

beforeSend
request started
.  .  .
response received
if fail then
 error 
 Promise fail
else
 dataFilter
 success
 Promise done
 Promise complete

Notice that the Promise methods can have multiple handlers assigned to them and they will all be executed and in the order that they were defined. The old event handlers can only have a single function to execute. 

As well as these "local" events there are also global event handlers that can be set to apply to all Ajax requests.

However it is important to note that global event handlers are never invoked during a JSONP or a cross domain script request as these do not use the XmlHttpRequest object for transport.  

All of the global handlers accept an event handler with the same form:

function(event,jqXHR,options)

They all also have to be attached to the document object.

The relationship between the global and local events is well described in the documentation:  

  • ajaxStart (Global Event)
    This event is triggered if an Ajax request is started and no other Ajax requests are currently running.
  • beforeSend (Local Event)
    This event, which is triggered before an Ajax request is started.
  • ajaxSend (Global Event)
    This global event is also triggered before the request is run.
  • success (Local Event)
    This event is only called if the request was successful (no errors from the server, no errors with the data).
  • ajaxSuccess (Global Event)
    This event is also only called if the request was successful.
  • error (Local Event)
    This event is only called if an error occurred with the request (you can never have both an error and a success callback with a request).
  • ajaxError (Global Event)
    This global event behaves the same as the local error event.
  • complete (Local Event)
    This event is called regardless of if the request was successful, or not. You will always receive a complete callback, even for synchronous requests.
  • ajaxComplete (Global Event)
    This event behaves the same as the complete event and will be triggered every time an Ajax request finishes.
  • ajaxStop (Global Event)
    This global event is triggered if there are no more Ajax requests being processed.

Notice that the ajaxStart/Stop events can be used to keep track of overall Ajax activity. Apart from this the global events are simply alternatives to the local events. 

For example you could use

$(document).ajaxSend(
 function(event,jqXHR, options){ 
  jqXHR.setRequestHeader('myHeader', 'myValue');
 });

in place of the beforeSend function. 

You can also turn off all global events by setting the global option to false.

Finally there is the context option. By default in all event handlers and callbacks this is set to object that is the result of merging the options set by ajaxSettings and the options specified in the call. So for example you could use:

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

in place of options.url.

Alternatively you can set this to any object that might be useful using the context option. For example:

options.context=$("body");

This sets this to a jQuery object wrapping the portion of the DOM corresponding to the body tag. After this you can write things like:

function(data,test,XHR){
 console.log(this.html()) ;
});

Notice that html() is a jQuery method and this is a jQuery result object. 

This sort of technique is only likely to be useful in situations where you need to change the object that the event handlers/callbacks operate on. In most cases it is easier to do the processing on the object explicitly e.g.

function(data,test,XHR){
 console.log($("body").html());
});

 

 
justjquery

 

Where Next

The  topic we still have to consider is how character encoding works. 

Summary

  • 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. 
  • However if you want to try to set a field on the native XMLHttpRequest you can use the xhrFields option.
  • 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. 
  • beforeSend specifies a function called just before the Ajax transport is started so that you can modify any aspect of the request. Typical uses of beforeSend are to set any request headers you might need.
  • If you register a status code handler using the statusCode function it will be called automatically if the server returns that code.
  • In most cases you only need to make use of the Promise that the ajax method returns. However before the use of the Promise object there were and still are the old event handlers.These are deprecated and you shouldn't use them if at all possible but you might need to know about them

 

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

 

Banner


JavaScript Jems - The Inheritance Tax

JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way.  In particular, it doesn't do inheritance  [ ... ]



JavaScript Jems - Objects Are Anonymous Singletons

JavaScript should not be judged as if it was a poor version of the other popular languages - it isn't a Java or a C++ clone. It does things its own way.  In particular, every object can be regard [ ... ]


Other Articles

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

raspberry pi books

 

Comments




or email your comment to: comments@i-programmer.info

 



Last Updated ( Thursday, 05 May 2022 )