When starting to program with AJAX it's always the programmer reminding themselves that this is not a brand new technology. It's just common or garden Javascript (even though it's normally stood under the very wide Web 2.0 umbrella).
It doesn't even move between browser as easily as one might like. The code required for Microsoft Internet Explorer is just a little bit different for the code required for browsers such as Firefox. However, that's not to say that AJAX is not incredibly useful. Using this simple technique it is possible for a web site designer to completely transform the look and feel of a web page. They can use just a few lines of code to push their work kicking and screaming into the 21st century.
An Overview of AJAX
Every AJAX web page works in the same way:
- the programmer uses Javascript to create an XML HTTP request object;
- they then use this object to send a request to (for example) a PHP page on a server
- the web page then (at some point) receives a response from the server
- the web page processes any information received and, typically, writes it somewhere on the browser screen
and that, in a nut shell, is Asynchronous Javascript and XML (commonly known as AJAX).
Adding an AJAX Library
It's worth repeating the fact that every AJAX web page works in the same way. The web page will:
- send a request for information to a server
- receive a response from the server
- update an area (such as a div) with the results of its server query
It is, therefore, sensible to store all of the AJAX functionality in a a Javascript library and (to start with) this library would look like:
If the programmer saved this code into "library.js" then they could then load it into any web page by using something like:
Of course, this code only creates the required object. The next stage is to do something interesting with it.
Adding AJAX Functionality
The aim of any AJAX application is to:
- send a request to a server in the form of a url
- update the browser with the results of that request.
This can be achieved by using a very simple Javascript function:
This function requires a target component to be defined on a web page:
and it's to here that the response will be written. It's then just a matter of creating a component that will call the function, for example a button:
And, if valid information is used, those few lines of code will produce a simple, but effective, first AJAX web page.