What's AJAX?
AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful browser features that have been around for years, but were overlooked by many web developers until recently when applications such as Gmail, Google suggest, and Google Maps hit the streets.
The two features in question are that you can:
- Make requests to the server without reloading the page
- Parse and work with XML documents
Step 1 – say "Please!" or How to Make an HTTP Request
In order to make an HTTP request to the server using JavaScript, you need an instance of a class that provides you this functionality. Such a class was originally introduced in Internet Explorer as an ActiveX object, called XMLHTTP. Then Mozilla, Safari and other browsers followed, implementing an XMLHttpRequest class that supports the methods and properties of Microsoft's original ActiveX object.
As a result, in order to create a cross-browser instance (object) of the required class, you can do:
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
(For illustration purposes, the above is a bit simplified version of the code to be used for creating an XMLHTTP instance. For a more real-life example, see step 3 of this article.)
Some versions of some Mozilla browsers won't work properly if the response from the server doesn't have an XML mime-type header. To satisfy this, you can use an extra method call to override the header sent by the server, just in case it's not text/xml.
http_request = new XMLHttpRequest();
http_request.overrideMimeType('text/xml');
Read more »