spacer
  • jQuery
  • UI
  • Mobile
  • Meetups
  • Forum
  • Blog
  • About
  • Donate
  • Download
  • Documentation
  • Tutorials
  • Bug Tracker
  • Discussion

jQuery API

Skip to content

Extending Ajax: Prefilters, Converters, and Transports

As of jQuery 1.5, $.ajax() provides three means to extend its functionalities for sending, receiving, and managing ajax requests:

Prefilters
Generalized beforeSend callbacks to handle custom options or modify existing ones
Converters
Generalized dataFilter callbacks that are called in response to a particular dataType being received that differs from what was expected
Transports
New in 1.5, these are used internally to issue requests by $.ajax

Prefilters

A prefilter is a callback function that is called before each request is sent, and prior to any $.ajax() option handling.

Prefilters are registered using $.ajaxPrefilter(), and a typical registration looks like this:

$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
  // Modify options, control originalOptions, store jqXHR, etc
});

where:

  • options are the request options
  • originalOptions are the options as provided to the ajax method, unmodified and, thus, without defaults from ajaxSettings
  • jqXHR is the jqXHR object of the request

Prefilters are a perfect fit when you need to handle custom options. For instance the following code would make it so $.ajax() automatically aborts a request with the same url if the custom abortOnRetry option is set to true:

var currentRequests = {};

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
  if ( options.abortOnRetry ) {
    if ( currentRequests[ options.url ] ) {
      currentRequests[ options.url ].abort();
    }
    currentRequests[ options.url ] = jqXHR;
  }
});

Prefilters can also be used to modify existing options. For example, the following proxies cross-domain requests through mydomain.net/proxy/:

$.ajaxPrefilter( function( options ) {
  if ( options.crossDomain ) {
    options.url = "mydomain.net/proxy/" + encodeURIComponent( options.url );
    options.crossDomain = false;
  }
});

It is also possible to attach a prefilter to requests with a specific dataType. For example, the following applies the given prefilter to JSON and script requests only:

$.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) {
  // Modify options, control originalOptions, store jqXHR, etc
});

Finally, it is possible to redirect a request to another dataType by returning the target dataType. For example, the following sets a request as "script" if the URL had some specific properties defined in a custom isActuallyScript() function:

$.ajaxPrefilter(function( options ) {
  if ( isActuallyScript( options.url ) ) {
    return "script";
  }
});

This would ensure not only that the request is considered "script" but also that all the prefilters specifically attached to the script dataType would be applied to it.

Converters

A converter is a callback function that is called when a response of a certain dataType is received while another dataType is expected.

Converters are stored into ajaxSettings and can be added globally as follows:

$.ajaxSetup({
  converters: {
    "text mydatatype": function( textValue ) {
      if ( valid( textValue ) ) {
        // Some parsing logic here
        return mydatatypeValue;
      } else {
        // This will notify a parsererror for current request
        throw exceptionObject;
      }
    }
  }
});

Converters are useful to introduce custom dataTypes. They can also be used to transform data into desired formats. Note: all custom dataTypes must be lowercase.

With the example above, it is now possible to request data of type "mydatatype" as follows:

$.ajax( url, {
  dataType: "mydatatype"
});

You can define converters "inline," inside the options of an ajax call. For example, the following code requests an XML document, then extracts relevant text from it, and parses it as "mydatatype":

$.ajax( url, {
  dataType: "xml text mydatatype",
  converters: {
    "xml text": function( xmlValue ) {
      // Extract relevant text from the xml document
      return textValue;
    }
  }
});

Transports

A transport is an object that provides two methods, send and abort, that are used internally by $.ajax() to issue requests. A transport is the most advanced way to enhance $.ajax() and should be used only as a last resort when prefilters and converters are insufficient.

Since each request requires its own transport object instance, tranports cannot be registered directly. Therefore, you should provide a function that returns a transport instead.

Transports factories are registered using $.ajaxTransport(). A typical registration looks like this:

$.ajaxTransport( function( options, originalOptions, jqXHR ) {
  if( /* transportCanHandleRequest */ ) {
    return {
      send: function( headers, completeCallback ) {
        /* send code */
      },
      abort: function() {
        /* abort code */
      }
    };
  }
});

where:

  • options are the request options
  • originalOptions are the options as provided to the ajax method, unmodified and, thus, without defaults from ajaxSettings
  • jqXHR is the jqXHR object of the request
  • headers is a map of request headers (key/value) that the transport can transmit if it supports it
  • completeCallback is the callback used to notify ajax of the completion of the request

completeCallback has the following signature:

function( status, statusText, responses, headers ) {}

where:

  • status is the HTTP status code of the response, like 200 for a typical success, or 404 for when the resource is not found.
  • statusText is the statusText of the response.
  • responses (Optional) is a map of dataType/value that contains the response in all the formats the transport could provide (for instance, a native XMLHttpRequest object would set reponses to { xml: XMLData, text: textData } for a response that is an XML document)
  • headers (Optional) is a string containing all the response headers if the transport has access to them (akin to what XMLHttpRequest.getAllResponseHeaders() would provide).

Just like prefilters, a transport's factory function can be attached to specific dataType:

$.ajaxTransport( "script", function( options, originalOptions, jqXHR ) {
    /* Will only be called for script requests */
});

The following example shows how a minimal image transport could be implemented:

$.ajaxTransport( "image", function( s ) {

  if ( s.type === "GET" && s.async ) {

    var image;

    return {

      send: function( _ , callback ) {

        image = new Image();

        function done( status ) {
          if ( image ) {
            var statusText = ( status == 200 ) ? "success" : "error",
            tmp = image;
            image = image.onreadystatechange = image.onerror = image.onload = null;
            callback( status, statusText, { image: tmp } );
          }
        }

        image.onreadystatechange = image.onload = function() {
          done( 200 );
        };
        image.onerror = function() {
          done( 404 );
        };

        image.src = s.url;
      },

      abort: function() {
        if ( image ) {
          image = image.onreadystatechange = image.onerror = image.onload = null;
        }
      }
    };
  }
});

Handling Custom Data Types

The jQuery Ajax implementation comes with a set of standard dataTypes, such as text, json, xml, and html.

Use the converters option in $.ajaxSetup() to augment or modify the data type conversion strategies used by $.ajax().

The unminified jQuery source itself includes a list of default converters, which effectively illustrates how they can be used:

// List of data converters
// 1) key format is "source_type destination_type" 
//    (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {

  // Convert anything to text
  "* text": window.String,

  // Text to html (true = no transformation)
  "text html": true,

  // Evaluate text as a json expression
  "text json": jQuery.parseJSON,

  // Parse text as xml
  "text xml": jQuery.parseXML
}

When you specify a converters option globally in $.ajaxSetup() or per call in $.ajax(), the object will map onto the default converters, overwriting those you specify and leaving the others intact.

For example, the jQuery source uses $.ajaxSetup() to add a converter for "text script":

jQuery.ajaxSetup({
  accepts: {
    script: "text/javascript, application/javascript"
  },
  contents: {
    script: /javascript/
  },
  converters: {
    "text script": jQuery.globalEval
  }
});

jQuery API

    • New or Changed in 1.7
    • Raw XML API Dump
    • Dynamic API Browser
    • jQuery API Book
    Keyboard navigation now available! Use up, down, tab, shift+tab, shift+upArrow and enter to navigate.

Browse the jQuery API

    • All
    • Ajax
      • Global Ajax Event Handlers
      • Helper Functions
      • Low-Level Interface
      • Shorthand Methods
    • Attributes
    • Callbacks Object
    • Core
    • CSS
    • Data
    • Deferred Object
    • Deprecated
    • Dimensions
    • Effects
      • Basics
      • Custom
      • Fading
      • Sliding
    • Events
      • Browser Events
      • Document Loading
      • Event Handler Attachment
      • Event Object
      • Form Events
      • Keyboard Events
      • Mouse Events
    • Forms
    • Internals
    • Manipulation
      • Class Attribute
      • Copying
      • DOM Insertion, Around
      • DOM Insertion, Inside
      • DOM Insertion, Outside
      • DOM Removal
      • DOM Replacement
      • General Attributes
      • Style Properties
    • Miscellaneous
      • Collection Manipulation
      • Data Storage
      • DOM Element Methods
      • Setup Methods
    • Offset
    • Plugins
      • Data Link
      • Templates
    • Properties
      • Properties of jQuery Object Instances
      • Properties of the Global jQuery Object
    • Selectors
      • Attribute
      • Basic
      • Basic Filter
      • Child Filter
      • Content Filter
      • Form
      • Hierarchy
      • jQuery Extensions
      • Visibility Filter
    • Traversing
      • Filtering
      • Miscellaneous Traversing
      • Tree Traversal
    • Utilities
    • Version
      • Version 1.0
      • Version 1.0.4
      • Version 1.1
      • Version 1.1.2
      • Version 1.1.3
      • Version 1.1.4
      • Version 1.2
      • Version 1.2.3
      • Version 1.2.6
      • Version 1.3
      • Version 1.4
      • Version 1.4.1
      • Version 1.4.2
      • Version 1.4.3
      • Version 1.4.4
      • Version 1.5
      • Version 1.5.1
      • Version 1.6
      • Version 1.7
gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.