How to work with AJAX (Asynchronous Javascript And XML)

What Is AJAX?

The AJAX (Asynchronous Javascript And XML) technique basically revolves around Javascript's capability to submit an HTTP request to a resource, and receive an XML document back as a result.

Download Code Sample (.ZIP, 4.44 kb)
Note: You will need to run this example on a web server such as Apache or IIS - This example will not work if viewed through your computer file system.

This is accomplished by using the XMLHttpRequest object. (The nomenclature of the object and instantiation thereof depends on the specific browser being used - it is neccesary to take this into account when writing AJAX-type scripts.)


var xhr;
if (window.XMLHttpRequest) // Gecko
	xhr = new XMLHttpRequest();
if (window.ActiveXObject) // Internet Explorer
	xhr = new ActiveXObject("Microsoft.XMLHTTP");
xhr.open("GET", "http://www.sanctumvoid.net/jsexamples/ajax/PhoneDirectory.xml", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded, charset=utf-8");

Another thing to keep in mind is that Internet Explorer and Gecko have different events that fire when the data has loaded. These differences are illustrated in the downloadable example.

This capability enables developers to submit requests to and receive results from a webserver without having to refresh the web page. The results are received as XML; developers can submit POST or GET requests to a webserver.

In most cases , a server-side script or program will be used to generate XML from a database. A common scenario would have a developer submit, for example, a sort column in the XMLHttpRequest object's POST request to the server-side script. The script would pass the sort order to the database with its query, and the XML would be displayed by the server-side script in the sorted order. All without the user having to refresh the web page.

To see a *simple* example (using a "GET" request to a static XML file) of AJAX in action, click the "Open Phone Book" button.