AJAX is a disruptive technology that's changed the way Web apps are developed and used. It allows for interactive pages and sits on the cutting edge of current Web trends.
It was the coming together of the XMLHttpRequest object being implemented in the majority of browsers, and the unveiling of GMail and Google Maps that inspired developers to rethink how they build Web pages.
The XMLHttpRequest object is what makes AJAX possible, it makes the asynchronous requests and determines how to handle the results. To create the object in most browsers we use the following code:
Now that we can create an XMLHttpRequest we need to consider when to create it. Although we have not made a request yet, one can see that it is possible to instantiate the XMLHttpRequest object prior to sending any requests or we could create the object within a method when we need it.
One problem with creating the object when you need it is that there exists no information about whether the client can create a XMLHttpRequest object or not. If a user arrives at your site and is unable create an XMLHttpRequest object you can accommodate them much more easier if you know from the earliest time possible that AJAX is not option.
It is never a good thing to have a user begin to interact with your Web application only to inform them that they cannot use it once they click on a submit button and have completely wasted their time filling out your form.
Whereas if the XMLHttpRequest creation is attempted at the start of the page, alternatives such as redirecting to a non-AJAX page become available before user interaction begins.
At this stage we have a page creating an XMLHttpRequest object when it is loaded, now let's use it for the purpose for which it was intended - making requests.
To do this we have to pass at least two parameters to the open method, most of these are straight forward to understand.
Url is the url string of the page we want to request. We cannot go and request any old page we like though, there is a sandbox that prevents us from accessing pages that are not the same domain as the page that is creating the request.
Async is what makes AJAX possible. Even though it is an optional parameter as defined in the API, for our purposes this parameter is mandatory and must be set to true - if it is set to false, the script will hold until a response is received. The default value for this parameter is true so you could choose not to set it, but in the interest of readability and maintainance, it is highly recommended to set this value.
User and Password are used for authentication if you choose to have it.
Once we set Async to true, we need to define a method to be called once the request state changes - this is done by setting the onreadystatechange property on XMLHttpRequest object.
Previously I said that we need to define a method to be called once the request state changes and that this is done by setting the onreadystatechange property; you should note that I said 'state changes', not 'complete' - for those are two completely different things. The best way to show this is by way of example, incorporating everything that we have learnt so far. Put the following in one file:
When the button is pressed we should notice that the readystate alert appears multiple times and eventually it will show the readyState equal to 4. Different browsers handle this differently, in Safari it counts nicely from 0-4 but in firefox it has 1 appear twice and 0 only appears on the first time it is run. Thankfully for us, we are only interested when the readyState is 4, but for the sake of completeness let's see what those numbers actually mean.
* 0: uninitialised - the object contains no data, prior to open being called
* 1: object is loading its data - prior to send being called
* 2: loaded - the request has been sent
* 3: interactive - the request is being processed and some data maybe available but is incomplete and thus unsafe to use
* 4: complete - the request is complete and the resultant data is safe to use
Armed with this new information we can change myReturnMethod to only have the alert appear when the request is complete.
Taking the previous code, let's change the url parameter of the open method to a file that does not exist:
If it were a regular http request we would expect a 404 error to appear - the same applies in AJAX with the status property. This property is read only and contains the HTTP status code of the request, in the case of our file it is 404. The same status codes we are used to in a regular http request still apply when working with AJAX. (Note that for this to work properly the page should be requested from an HTTP server, if it is read from the filesystem the status code will always be undefined.)
Therefore we need to add an if statement that tests whether the request was successful, if it is a response code of 200 will be returned. If it is not successful we need to be able to handle the error should we choose to.
Now that we are able to successfully complete an AJAX request, we need to do something with the results. There are two ways that we can do this, by using the responseText or the responseXML properties. The easiest way to fetch the data that the server has returned is to use the responseText property as it returns the data as plain text. This way the data can be anything that we want it to be: simple text responses, comma delimited values or an entire book in one string. In our return method we will output the responseText in an alert, this will output the entire contents of the file we are requesting.
At this stage if you have not put any contents into the file we have been requesting, another_file.html, you should do so.
Now that we know how to create a request and fetch the results, one question that has yet to be answered is, when should we use AJAX?
Naturally with such a new technique there are extremes in both opinions, some Web developers think that life would be easier if AJAX just disappeared altogether while others would love nothing better than to see an entire site written within an AJAX framework. As is usual with such things, the truth of the matter is somewhere in between these two points. When using AJAX on your site you should be aware of the consequences of your decision. Firstly any page you manipulate with AJAX is not guaranteed to be bookmarkable. The usage of AJAX introduces a "state" into your Web site which will not enable users to return to any state except the initial state. This is because the url does not change in the user's broswer - if it did change, then there would be no need for AJAX.
|All times are GMT +5.5. The time now is 01:54.|