Getting Started With jQuery - Advanced Ajax Transports
Written by Ian Elliot   
Monday, 09 November 2015
Article Index
Getting Started With jQuery - Advanced Ajax Transports
JSONP
Custom prefilter

 

Image Transport 

Until recently there haven't been many options for new transports because there aren't many different ways of starting a data transfer in a browser. The two best known are the image tag transport and the hidden frame download. You can find jQuery plugins for both types of transport. Today you also have the option of using sockets to implement any transport you care to invent.

Although the documentation gives an example of an image transport it is worth providing a simpler implementation so that you can see how a real transport might be created. The reason that this implementation is simpler is that it does no error handling. 

The transport object factory is simply:


function myTransportFactory(options,
                      originalOptions,jqXHR){
 var myimage;
 var transport={
  send:function(headers,callback){
   myimage=new Image();
   myimage.onload=function(){
    callback(200,"success",{image:myimage});
   };
   myimage.src=options.url;
 },

 abort:function(){
  myimage=null;
  }
 };
 return transport;
}

This follows the same outline as the previous example. It creates and Image object, sets its onload event handler and then starts it downloading by setting its src property to the url. Notice that when the Image has loaded the onload function simply calls the callback with the image. 

To use this new transport you would write something like:

$.ajaxTransport("image",myTransportFactory);
var options={};
options.url="test.jpg";
options.method="get";
options.dataType="image";

$.ajax(options).then(
 function(data){
  $("body").append(data);
  console.log(data);

 });

After registering the transport factory to handle the image type the Ajax request is set up and the url is set to test.jpg. When the file is loaded it the Image object is added to the DOM in the done method. 

If you run this program then you will see the image appear in the web page and you will see an image tag displayed in the console. 

To make this into something more robust you would have to add error handling.

 

justjquery

 

Custom prefilters

You can do most of the things that you need to with a custom transport but sometimes you need to modify the way things are setup before the transport is invoked. For example, in the case of the JSONP transport it is necessary to set up the wrapper function before the transport is called to load and run the script. 

To allow you to modify things before the transport is put into action you can create a custom prefilter. If you have read the section on creating a custom transport then the general outline of what is to follow will be familiar. To register a prefilter for a particular data type you would use the ajaxPrefilter method.

ajaxPrefilter(dataTypes,handler)

The handler is a function that will be called for the specified datatypes before the appropriate transport is invoked.

Notice that unlike the transport the handler is the function that is called. The handler is:

function handler(options, originalOptions,jqXHR)

where the parameters are the same as in the transport registration - options, the options for the call including defaults, originalOptions the options explicitly set by the user and the jqXHR object generated by the request. The handler can also return a datatype if the request is better handled as a completely different data type. This is what the JSONP prefilter does, it sets up the wrapper function and then returns "script" so that the script prefilter, transport, converters etc are used after the prefilter has set everything up correctly.

For example, if you want to do a task before the image transport is called you could use:

$.ajaxPrefilter("image",
 function(options,originalOptions,jqXHR){
  console.log("prefilter");
 });

Of course code that you put in the prefilter could have been put into the start of the transport object, assuming that there is a custom transport object. If the prefilter can set things up and then hand off to an existing transport then it is worth using a prefilter. Similarly, if a prefilter can be used with more than one data type or more than one transport then it is better to write a single prefilter function than to put the same code into each of the data types or transport objects. 

Where Next

Even though we are deep into jQuery's Ajax API there are still things we haven't touched on. In particular there is the mysterious jqXHR object and the whole, slightly confused issue of Ajax events and what happens when. Following this we need to look into the problems causes by character encoding.  

Summary

  • Script transport is handled differently depending on whether it is a same site or cross site request. For a same site request the script is downloaded as text and executed. For a cross site request the script is add to the DOM and the browser deals with it. 
  • JSONP is a way to download data possibly cross site by converting it into a script request. 
  • A JSONP request will use XMLHttpRequest transport for a same domain request and a script transport for a cross domain request.
  • If you are writing your own server side code then simply let jQuery generate a name for the wrapper function. Make the server wrap the JSON with a function as specified in the callback parameter and don't implement anything on the clientside. You can treat the whole interaction as if it was an Ajax call with the JSON data delivered to the then method as usual. 
  • If you have to write a client to work with a server that has already been set up to use a specific wrapper name then specify the jsonpCallback option to set the name of the wrapper function that the sever uses. 
  • If the server has been set up to wrap the JSON in a function specified by some other parameter use the jsonp option to specify the name of the parameter.
  • You can implement your own transport using the ajaxTransport function.
  • A prefilter function can also be specified which is called before the transport function.

 

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 )