Simple AJAX Example
This aims to be the easiest possible example demonstrating AJAX (Asynchronous JavaScript and XML).
AJAX is a technique rather than a technology: It describes how JavaScript can be used to pull data from the server using the XML HTTP Request object and then insert this data into the website using DOM. This is done asynchronously – that is, in the background, without having to refresh the whole page. The technology which AJAX is based on has already been available for a while, the combination is what makes it new.
You can try the examples online or download them and run them locally (except for the PHP script, that would require a webserver with PHP).
1. The DOM
The Document Object Model is the internal representation of your website. The DOM is accessible by JavaScript and provides a way to programmatically insert, remove and modify tags in your website (except that they are called elements or nodes instead of tags, because the DOM manipulates the data model in memory and not the representation as XML). This example shows how to set the content of the element with the id “foo” to “Hello, AJAX world!”:
<script type="text/javascript">
function replace() {
document.getElementById('foo').innerHTML = "Hello, <b>AJAX</b> world!";
}
</script>
<p><a href="javascript:replace()">Replace Text</a></p>
<div id="foo">
Hello, world!
</div>
Try here: dom.html
Read the Rough Guide to the DOM for more information.
2. The XML HTTP Request object
The XML HTTP Request object is used to make HTTP requests. The following code will download the file test.txt and display its contents as a message box.
This is the content of test.txt
Save as test.txt.
<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
http.open("GET", "test.txt");
http.onreadystatechange=function() {
if(http.readyState == 4) {
alert(http.responseText);
}
}
http.send(null);
</script>
Try here: httpreq.html
XMLHttpRequest Properties
- readyState
– 0 = UNINITIALIZED; open not yet called
– 1 = LOADING; send for request not yet called
– 2 = LOADED; send called, headers and status are available
– 3 = INTERACTIVE; downloading response,
responseText only partially set
– 4 = COMPLETED; finished downloading response - responseText
– response as text; null if error occurs or ready state < 3 - responseXML
– response as DOM Document object; null if error occurs or ready state < 3 - status – integer status code
- statusText – string status
Learn more about the XMLHttpRequest object on Wikipedia and in Using the XML HTTP Request object.
3. Combining the Two = AJAX
Combining DOM manipulation with the XMLHttpRequest gives us AJAX.
<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
function replace() {
http.open("GET", "test.txt", true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
document.getElementById('foo').innerHTML = http.responseText;
}
}
http.send(null);
}
</script>
<p><a href="javascript:replace()">Replace Text</a></p>
<div id="foo">
Hello, world!
</div>
Try here: ajax-simple.html
Note the third argument to http.open(), which I have set to true. This is the async argument which sends the request to the background. AJAX would not be AJAX without that!
4. Useful Frameworks
Doing AJAX by hand is certainly possible and helps understanding it, but using a good library makes the whole experience more comfortable. Read Painless JavaScript Using Prototype talking about the Prototype library, and watch Mochikit’s screencast.