Ajax (Asynchronous Javascript and XML) defines the use of multiple technologies, especially
Javascript,
XmlHttpRequest,
DOM (Document Object Model) and
XML, to create an interactive web application.
In "normal" web application, when user sends a request, be it by clicking on a link or clicking on a button or any other ways, web server responds to the request by sending a new page back to the user. This can be very inefficient if only a small portion of the page changes as a result of the request.
With Ajax, we can remove this inefficiency by having an XmlHttpRequest object handle user requests in the background, and then dynamically update portions of the website as necessary (as opposed to reloading the whole page) with DOM.
As mentioned earlier, an
XmlHttpRequest object can be used as a means of communication between client (web browser) and web server that is transparent to the user.
To simplify the creation of XmlHttpRequest object, use the following function:
Notice that we have several levels of try-catch blocks in the code above? The first two will handle different versions of Internet Explorer, and the other one will handle other browsers that support XmlHttpRequest (e.g.: Firefox, Mozilla, Netscape, Safari).
Refer to the code and inline comments below:
In the above code, we send a "get" request to the web server for the test.php script. When we successfully receive a response from the server, we simply display whatever the script outputs in a Javascript alert box. In real life applications, instead of popping up an alert, we may want to update some portions of the page instead. To do so, simply replace line 18 in the code above.
It is also possible to request a script that returns an XML file, in which case we can access the XML object with the responseXML property of our XmlHttpRequest object (i.e.: xhr.responseXML in the sample code above).
Create an HTML file that contains the above Javascript functions:
Create a PHP file called test.php which simply outputs some text:
If you do it right, when you click on "Get message from server", you should get a Javascript alert: "Hello World!".
Check out
Demo 1 below to see this in action.
Demo 1 - The script above in action
Demo 2 - The script above that prints out server's message to the screen
Demo 3 - Dynamically checks the price of an item when they are selected