Introduction
This page covers the basics of setting up a web page to use Ajax. Ajax stands for Asynchronous JavaScript with XML and really refers to a style of web page development. Instead of the standard request and response cycle of a regular web page, requests are made using JavaScript in the browser. The script then handles making the request for data and formatting the response.
The examples covered here are a summary of the techniques covered in two very excellent books. Please refer to them if you need more information on the subject.
| Bulletproof Ajax | PPK on JavaScript |
Getting a Text File with Ajax
For the first example, a simple text file is retrieved using Ajax.
A quick review of the important parts of the example is in order.
- if statement - The first part of the script is a big if statement (lines 7 to 24) that defines the
httpObjectthat makes the actual request. The statement creates the object for a standards based browser (Mozilla, Safari) or a Microsoft based browser. - getMsg - The
getMsgfunction (lines 26 - 35) makes the actual request for data from the server. Line 29 defines an event handler for a response from the server. When a response is received, the handler function defined on line 30 is called. Line 33 opens the actual connection to the server and specifies the resource to retrieve. Since this aGETrequest and no data is sent to the server,nullis sent on line 34. If this were aPOSTrequest, the data would be sent on line 34. - handleRequest - The request handler on lines 38 to 46 checks for a positive response from the server. Response 304 indicates it is ok to use a cached document so it is check in addition to 200. The response text is sent to the update function which updates the document.
That covers the hightlights.
Retrieving a Date with Ajax
Why don't not try something a little more useful? The following example extends the previous example a little bit. Instead of reading from a file, a PHP script is called with returns the current date and time. This can be called and inserted in the page. Each time the user clicks on the link, the date is updated on the page without any refresh.
Note much has changed from the first example. Line 33 calls an actual PHP script instead of a text file. The PHP script generates the date.
Here is the source code for the PHP script used to generate the date.
That completes this quick overview of an Ajax page. See the books linked above for more information on the subject.