Getting Started With jQuery - Ajax The Basics
Written by Ian Elliot   
Monday, 24 August 2015
Article Index
Getting Started With jQuery - Ajax The Basics
Promises and Ajax
Load & Where Next?

Promises and Ajax

If this is as complicated as your Ajax use is and is going to be then you can get way with simply using the callback form of get and the other Ajax methods. However as demonstrated in earlier chapters promises are worth using if you are trying to build an asynchronous processing chains.

For the moment all you need to know is that all jQuery Ajax calls return an jqXHR object which is a super-set of a promise object it is a promise with extras. 

A promise object and hence a jqXHR object has two important methods 

then(doneFunction,failFunction) used to set a function that is called when the Ajax task has completed successfully and a function that is called when the Ajax task fails for some reason.

catch(failFunction) used to set a function that is called when the Ajax task has failed. It is equivalent to then(null,failFunction) 

As all promise methods return a promise object you can chain method calls on a jqXHR object just as you would with a promise. There are many other methods that the jqXHR inherits from the promise but in most cases you shouldn't make use of them unless you have a really good reason to. For example, as explained in earlier chapters, the done function looks like an equivalent to then(function,null) but it isn't because it doesn't chain like the then and catch methods. 

You can also use the always function which runs its callbacks no matter what state the promise settles to as long as it is at the end of the chain. In this role it acts as a cleanup function. 

The other methods of the jqXHR object are inherited from the browsers native XMLHttpRequest object more of which later. 

For example the previous load of "mydata.txt" can be written:

$.get("mydata.txt")
 .then(function(data){alert(data)});

Things get a little more interesting when you also define what is to happen if things go wrong and/or a clean up routine: 

$.get("mydata.txt").then(
                    function (data) {
                     alert(data);
                    },
                    function () {
                     alert("error");
                    })
                   .always(
                    function () {
                     alert("cleanup");
                    });

 

Of course you don't have to define a handler for each of the events but this is the easiest way to do the job.

The parameters passed to the callbacks allow them to manipulate the data returned or examine the status of the call. The two function used in the then accept three parameters: 

then(function( data, textStatus, jqXHR )
     function( jqXHR, textStatus, errorThrown )

and the always function uses either of the above parameter schemes depending on the sucess or failure of the call. That is:

always(function( data, textStatus, qXHR )

if successful or

always(function( jqXHR, textStatus, errorThrown )

if fail

data is the returned data.  

textStatus is object with a string value equal to one of:

"timeout"
"error"
"notmodified"
"success"
"parsererror"

errorThrown is a string containing the message returned by the server. Obviously the range of possible responses depends on the server.

jqXHR is an object that can be used to find things out about the Ajax request. It is a superset of the browser's XMLHttpRequest object and has at least the following properties. 

responseText - the data returned. 

responseXML - the data if it is HTML or XML 

status - HTTP result code

statusText - HTTP result code text e.g. OK

and methods:

getAllResponseHeaders()  get all headers as a single string

getResponseHeader("header") get the specified header as a string

For example:

$.get("mydata.txt")

 .then(
      function (data,textStatus,jqXHR ) {
       alert(jqXHR.getResponseHeader("Host"));
      });

 

Data Format 

Exactly how the data is passed to the function depends on the MIME type of the response. This is usually set by the server as a header but jQuery will attempt to guess the right format if it isn't set.

Notice that in many cases the response from the server will be generated by a program - a PHP page say - but you can just specify the file of data you want transmitted and the server will load it and send it. When a program generates the data it is usual to make sure a header is properly set. When data is downloaded from a file the headers are usually left to the server. 

More on headers and MIME in the following chapter.

If you know the format of the data you can specify it using a final parameter. The only complication is that you have to use place holders for the unused second and third parameters.

For example to tell jQuery that the file is XML you could use: 

$.get("mydata.txt",null,null,"xml")

  .done(
    function (data) {
      alert(data);
    });

In this case data would be an XML root element of the tree constructed from the data transmitted. If the file doesn't contain XML data then you get an error condition.

The possibilities are:

  • xml    -   XML root element
  • json   -  JSON object
  • jsonp -  JSONp object
  • script -  JavaScript file
  • html   -  String
  • text    -  String

If the data cannot be interpreted in the way you have set then an error is generated. 

There are also some easy to use Ajax methods that will get JSON or Script data directly. 

getJSON(url) 

will retrieve a JSON object from the specified url and 

getScript(url)

will retrieve a script from he specified url.

Both work in the same way as the basic get and both return a Promise object.

If the data isn't in the correct format then an error occurs and the fail method of the Promise is called.

For example:

$.getJSON("myJSON.json")
 .then(
   function(data){
    alert(data.name);
   },
   function(){
    alert("error");
   });

 

assuming that the file myJSON has a name property set to some string e.g. 

{
 "name": "Ian"
}

In the case of getScript the JavaScript is loaded and ready to run. It is also provided as a string as the first parameter to the done method. 

For example:

$.getScript("myScript.js")
 .done(
   function(data){
    alert(data);
   },
   function(){
    alert("error");
   });

If myScript.js contains:

alert("hello remote script");

then you wil see "hello remote script" before you see the alert listing the program. That is, the script is added before the done method gets to run. 

A more reasonable example would be if myScript.js contains:

function doSomething(){
 alert("hello remote script");
};

Then it could be loaded and used something like:

$.getScript("myScript.js")
 .then(
   function(data){
    alert(data);
    doSomething();
   },
   function(){
   alert("error");
  });

The JavaScript is executed in the global context. 

justjquery

Load

Finally there is one more variation on the basic get method - the load method. This performs a basic get, but it is slightly more integrated with the rest of jQuery in that it will set the HTML content of any matched elements. 

However load is a strange method and doesn't fit in with the other Ajax methods. For example, it doesn't return a Promise object so you have to specify a success function. It does return a jQuery object so it can be chained. 

For example:

$("body").load("myData.txt");

loads myData.txt and sets it as the body tag's HTML. Notice that if there are no matching elements the Ajax call isn't performed. 

If you want to do something after the HTML has been loaded you need to supply a callback:

$("body").load("myData.txt",
                function(data){
                 alert(data);
                });

Notice that the callback isn't just a success callback. It is a post processing callback.

The function that you supply is called once for each element in the selected set and this is set to each of the elements in turn. This allows you to scan through and modify the HTML that you have just loaded. 



Last Updated ( Thursday, 05 May 2022 )