Getting Started With jQuery - Ajax The Basics |
Written by Ian Elliot | ||||
Monday, 24 August 2015 | ||||
Page 2 of 3
Promises and AjaxIf 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:
Things get a little more interesting when you also define what is to happen if things go wrong and/or a clean up routine:
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:
and the always function uses either of the above parameter schemes depending on the sucess or failure of the call. That is:
if successful or
if fail data is the returned data. textStatus is object with a string value equal to one of: "timeout" 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:
Data FormatExactly 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:
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:
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.
will retrieve a JSON object from the specified url and
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:
assuming that the file myJSON has a name property set to some string e.g.
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:
If myScript.js contains:
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:
Then it could be loaded and used something like:
The JavaScript is executed in the global context.
LoadFinally 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:
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:
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 ) |