The Ajax Low-Level Interface JQ Home  <<  JQ Advanced  <<  The Ajax Low-Level Interface

In this lesson we investigate the methods that make up the jQuery Low-Level Interface.

Before we get started with the lesson lets just have a quick reminder of what Ajax is all about. The term Ajax stands for Asynchronous JavaScript and XML and allows us to interrogate a server and bring back information with which we can update our webpages, without doing a page refresh. This in turn makes our pages faster and gives them the feel of desktop applications to our users and thus makes the whole user interaction a more rewarding experience.

jQuery Ajax methods return a jqXHR object which is a superset of the browser's native XMLHttpRequest object. The jqXHR object implements the Promise interface, giving it all the properties, methods, and behavior of a Promise as discussed in The Deferred Object lesson.

  • A jqXHR object will expose the following properties and methods for backward compatibility with the XMLHttpRequest object:
    jqXHR Object Description
    Methods
    abort()Cancels the currently executing request.
    getAllResponseHeaders()Returns a string containing the names and value of all response headers.
    getResponseHeader(name)Returns the value of the specified response headers.
    .overrideMimeType()Used in the beforeSend() callback function, to modify the response content-type header.
    setRequestHeader(name, value)Set a request header using the specified name and value.
    Properties
    readyStateAn integer indicating the current state of the request.
    responseTextUnderlying request responded with text.
    responseXMLUnderlying request responded with xml.
    statusResponse status code returned from the server.
    statusTextStatus text message returned by the response.

Ajax Low-Level Interface Methods

The three methods which make up the jQuery Low-Level Interface are listed in the table below, click a link to go to examples for that method. These methods allow us complete control over our Ajax requests and will be called 'under the bonnet' by all the other jQuery Ajax methods in the suite.

Low-Level Interface Methods Description
jQuery.ajax()Perform an asynchronous HTTP (Ajax) request.
jQuery.ajaxPrefilter()Filter custom Ajax settings or modify the existing settings, before sending each request and before they are processed by the $.ajax() method.
jQuery.ajaxSetup()Initialize default settings for future Ajax requests.

The jQuery.ajax() Method Top

Perform an asynchronous HTTP (Ajax) request

The $.ajax() method is the all singing, all dancing jQuery Ajax method and under the bonnet underpins any Ajax requests sent by jQuery. The method comes with a plethora of settings, which are described in detail in the reference section, giving us a great deal of flexibility when making our requests. There are other jQuery Ajax methods such as jQuery.get() and jQuery.post() which are easier to use for general purpose requests.

We will be using the jQuery.ajax( url [, settings] ) signature for our example which will perform an asynchronous HTTP (Ajax) request to be sent to the specified url, optionally passing some request settings.

The second signature jQuery.ajax( settings ) performs an asynchronous HTTP (Ajax) request, optionally passing some request settings.

Examples of both signatures are available in the reference section.

In the example below when we press the left button the first time, we create an Ajax request, passing the datatype along with the error() callback function. For this example the request will fail as the 'get11.js' asset does not exist. Therefore the error() callback setting activates and outputs a message.

In the example below when we press the right button the first time, we create an Ajax request, passing the datatype along with the success() callback function. For this example the request will succeed as the 'get1.js' asset does exist. Therefore the script for the 'get1.js' asset executes as we have passed across a datatype of 'script'. After this the success() callback setting activates and outputs a message telling us the request succeeded.


$(function(){
  $('#btn1').one('click', function(){
    $.ajax( "../../js/get11.js", {
      dataType: "script",
      error: function() { 
        $('#div1').append('The request failed! <br><br>');
      }
    });
  });
  $('#btn2').one('click', function(){
    $.ajax( "../../js/get1.js", {
      dataType: "script",
      success: function() { 
        $('#div1').append('The request was a sucesss! <br><br>');
      }
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../js/get1.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div1').append('Message from get1.js: ' + someText + '<br>');
});

div1. Some initial text.

Press the button below to action the above code:

               

The jQuery.ajaxPrefilter() Method Top

Filter custom Ajax settings or modify the existing settings, before sending each request and before they are processed by the jQuery.ajax() method.

The jQuery.ajaxPrefilter() method allows us to do pre-filtering on an ajax request just before the call and will always be called prior to the request if available.

We will be using this methods only signature jQuery.ajaxPrefilter( [dataTypes], handler(settings, localSettings, jqXHR) ) for our example which will filter custom Ajax settings or modify the existing settings, before sending each request and before they are processed by the jQuery.ajax() method.

In the example below when we press the left button the first time, we create a custom setting using the jQuery.ajaxSetup() method. We then run the userRequest() function and within that create a deferred/promise to map to the output from a request. After this we call the jQuery.ajaxPrefilter() method and abort any request to the page not from a special user. We output a message confirming this.

In the example below when we press the right button the first time, we create a custom setting using the jQuery.ajaxSetup() method. We then run the userRequest() function and within that create a deferred/promise to map to the output from a request. After this we call the jQuery.ajaxPrefilter() method and accept the request to the page from a special user. We output a message confirming this, return the Promise of the jqXHR and then output messages accordingly.


$(function(){
  $('#btn3').one('click', function(){
    $.ajaxSetup({
        specialUser: false
    });
    checkUser();
  });
  $('#btn4').one('click', function(){
    $.ajaxSetup({
        specialUser: true
    });
    checkUser();
  });
  function checkUser() {
    returnedPromise = userRequest();
    /*
     * Here we can check our returned promise which we mapped from our Ajax request.
     * 
     * if .done is a special user.
     * if .fail is not a special user.
     */
    returnedPromise.done( function() {
        $('#div2').append('Special user! <br>');
    });
    returnedPromise.fail( function() {
        $('#div2').append('This is not a special user! <br><br>');
    });
  }
  
  function userRequest() {
    var ourDeferred = new $.Deferred();
    var userPromise = ourDeferred.promise(); 

    $.ajaxPrefilter( function(settings, localSettings, jqXHR) {
       if(settings.specialUser) {
          $('#div2').append('Special user setting exists! <br>');
       } else {
          $('#div2').append('No special user setting, abort! <br>');
          jqXHR.abort();  
       }
    });
    var jqxhr = $.ajax({
       type: "GET",
       url: "../../js/get4.js",
       dataType: "script"
    });
    jqxhr.done(function(data, status, xhr) {
      $('#div2').append('Special user with prefilter, so resolve the deferred! <br>');
      ourDeferred.resolve();
    });
    jqxhr.fail(function(jqXHR, status, error) {
      $('#div2').append('Error with Ajax request! ' + status + ' ' + error + '  <br>');
      ourDeferred.reject();
    });
    // Return the jqXHR Promise object
    return userPromise;
  }
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../../js/get4.js")
 * is shown below.
 */
$(function(){
  var someText = 'Special users only. ';
  $('#div2').append('Message from get4.js: ' + someText + '
'); });

div2. Some initial text.

Press the button below to action the above code:

               

The jQuery.ajaxSetup() Method Top

Initialize default settings for future Ajax requests.

The jQuery.ajaxSetup() method allows us to make default settings for all Ajax requests on the current page.

We will be using this methods only signature jQuery.ajaxSetup( settings ) signature for our example which will initialize default settings for future Ajax requests.

In the example below when we press the left button we create an Ajax request, passing the complete() callback function. The only output we see is from this callback as the request has no settings for the request apart from this.

In the example below when we press the right button the first time we create some settings for url and dataType using the $.ajaxSetup() method. If we then press the left button after this our request works as can be seen from the output messages. This is because the request will use the settings we created using the $.ajaxSetup() method for the url and dataType settings and therefore have enough information to successfully complete the request.


$(function(){
  $('#btn5').on('click', function(){
    $.ajax({
      complete: function() { 
        $('#div3').append('The request ended! <br>');
      }
    });
  });
  $('#btn6').one('click', function(){
    $.ajaxSetup({
      url: "../../../js/get5.js", 
      dataType: "script"
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../../../js/get5.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div3').append('Message from get5.js: ' + someText + '<br>');
});

div3. Some initial text.

Press the button below to action the above code:

               

Getting a Promise Back From Our Ajax Requests

As mentioned briefly in the last lesson we can use the .when() method to check the outcome of multiple deferreds and then act accordingly when all have resolved or one has rejected. The jqXHR object returned from Ajax requests is a deferred under the bonnet and thus we can map a promise from our returned request for use later in our code and also have access to the deferred methods to improve our status replies etc. The following code can be used as a template for doing this:



$(function(){
  function getPromise() {
    returnedPromise = userRequest();
    /*
     * Here we can check our returned promise which we mapped
     * from our Ajax request.
     */
    returnedPromise.done( function() {
      .....
    });
    returnedPromise.fail( function() {
      .....
    }); 
    /*
     * Here we could check for mutiple deferreds.
     */
    $.when( returnedPromise, returnedPromiseN ).done( function() {
      .....
    });
    
  }
  
  function getPromise() {
    var ourDeferred = new $.Deferred();
    var userPromise = ourDeferred.promise(); 
    /*
     * Some sort of generic request to get back a jqXHR object.
     */
    var jqxhr = $.ajax({
      type: "GET",
      url: "../../../js/get3.js",
      dataType: "script",
      data: { someData: someData }
    });
    /*
     * Do something with done and fail.
     */
    jqxhr.done(function(data, status, xhr) {
      if (!true) {
       ourDeferred.reject(jqxhr, 'error');
      } else {
       ourDeferred.resolve(data, status, xhr);
      }
    });
    jqxhr.fail(function(jqxhr, status, error) {
      ourDeferred.reject(jqxhr, status, error);
    });
    // Return the jqXHR Promise object
    return userPromise;
  }
});

Lesson 8 Complete

In this lesson we looked at the the Ajax Low-Level Interface.

Related Tutorials

jQuery Advanced - Lesson 9: Ajax Shorthand Methods
jQuery Advanced - Lesson 10: Ajax Helper Functions
jQuery Advanced - Lesson 11: Ajax Global Event Handlers

Reference

Methods

Events - .on() method
Events - .one() method
Manipulation - .append() method
Ajax Low-Level Interface - jQuery.ajax() method
Ajax Low-Level Interface - jQuery.ajaxPrefilter() method
Ajax Low-Level Interface - jQuery.ajaxSetup() method