Getting Started With jQuery - Advanced Ajax To The Client
Written by Ian Elliot   
Monday, 12 October 2015
Article Index
Getting Started With jQuery - Advanced Ajax To The Client
The Standard DataTypes
Type Converters
The dataFilter function

An alternative multi-step approach

If you are implementing a completely new data type then creating a new text to newtype converter and registering a suitable header seems reasonable. However if what you have is a modification to an existing data type then perhaps a two or even multi-stage process is better. 

For example, jsond is just a development of JSON so why not accept JSON, allow jQuery to process it and then convert it to jsonp. 

For example, if the server sends a standard JSON header:

<?php
header("Content-Type:application/json;
                         charset=UTF-8");
$cdata='{"first": "Ian","last":"Elliot",
           "bday":"2013-10-21T13:28:06.419Z"}';
echo($cdata);
?>

You can allow jQuery to perform the conversion to JSON and then create a converter from json to jsond:

var options={};
options.url="process.php";
options.method="get";
options.dataType="jsond";
options.converters={"json jsond":
 function(data){
  data.bday=new Date(data.bday);
  return data;
 }};

$.ajax(options).then(
 function(data){
  console.log(data);
 });

Notice that now the dataType is jsond and we don't have to register a new header for the type. Also notice that the converter is now json to jsond rather than text to jsond. With these changes jQuery automatically calls its own text to json converter and then calls the json to jsond converter and notice that you don't have to explicitly convert the text data to JSON. 

If you don't want to rely on the header from the server you could write the dataType as

options.dataType="json jsond";

which forces the conversion sequence text->json->jsond no matter what the headers are. 

To summarise:

you can create a custom data type by defining converter functions that convert text to your new data type. 

if you want jQuery to recognize a Content-Type header for your new data type you have to define a mapping from the new data type name to the specific header using a regular expression.

Be careful that your regular expression isn't invalidated by an earlier expression that matches everything your's does.

You can override existing data type converters in the same way.

You can extend data type converters by chaining data types in the dataType option - the converters are called in the specified sequence.

The dataFilter

There is one final function that you can place into jQuery's processing pipeline - the dataFilter. This  is a function that is called right after the raw data has been received. The function is passed the raw data as its first parameter and the dataType specified as the second parameter. The function returns the raw data modified as required. 

For example, to include a dataFilter in the previous data converter program:

var options={};
options.url="process.php";
options.method="get";
options.dataType="json jsond";
options.dataFilter=function(data,datatype){
  console.log(data);
  console.log(datatype);
  return data;
 };
options.converters={"json jsond":
 function(data){
  data.bday=new Date(data.bday);
  return data;
 }};
$.ajax(options).then(
  function(data){
  console.log(data);
 });

 

If you run this program with the PHP file given in the previous section as the server then you will see:

{"first": "Ian","last":"Elliot",
     "bday":"2013-10-21T13:28:06.419Z"}
index.php:55:2
json jsond

Which is the raw JSON string and the data type as set by the dataType option. 

The idea is that you use the dataFilter to "sanitize" or otherwise modify the raw data received before it is passed on to the converters. 

Where Next

Topics that we have left to cover are how Script and JSONP work; global events, headers and how character encoding works. 

Summary

  • You can use accepts to indicate the  type of data the client wants back from the server as indicated in the Accept request header and dataType to set the type of data the client expects back from the server - a selection of xml, html, script, json, jsonp or text. 

 

  • Html data is returned as a String
  • Script from the same origin is downloaded as text and then executed.
  • json is converted to suitable JavaScript object with some limitations
  • xml is converted to an XML object
  • You can create your own type converters which take on type to another. These are registered using options.converters.
  • You can create your own custom types but these have to be connected to the types specified in the headers returned by the server using the contents option.
  • Type converters can be chained so that they are automatically called to converts one time into another. For example text to json followed by json to jsond.
  • There is also a data filter function which is called before any of the converters. Specified using the dataFilter option.

 

 

 

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 )