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 <div> 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
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. Cool AJAX example
While the previous example fully demonstrated AJAX, it was totally boring. Including the contents of a static file into the page could have been done much easier, you might say. However, AJAX becomes powerful when combined with a server-sided script. Consider the following PHP script, which validates a user name entered into a form. The name chosen has to be at least three letters long and must still be available:
<?php
function validate($name) {
if($name == '') {
return '';
}
if(strlen($name) < 3) {
return "<span id=\"warn\">Username too short</span>\n";
}
switch($name) {
case 'bob':
case 'jim':
case 'joe':
case 'carol':
return "<span id=\"warn\">Username already taken</span>\n";
}
return "<span id=\"notice\">Username ok!</span>\n";
}
echo validate(trim($_REQUEST['name']));
?>
Save as validate.php.
<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
function validate(user) {
http.abort();
http.open("GET", "validate.php?name=" + user, true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
document.getElementById('foo').innerHTML = http.responseText;
}
}
http.send(null);
}
</script>
<h1>Please choose your username:</h1>
<form>
<input type="text" onkeyup="validate(this.value)" />
<div id="foo"></div>
</form>
Try here: ajax-cool.html
Now enter a name into the text field. Try bob, jim, joe or carol. The <div> will
update as you type, giving you information on whether your username is valid. Also note
the http.abort();, which will abort the previous request, if a new one
comes in. This is useful when the user types very quickly. The script could probably
improved by waiting a couple of seconds after the user has typed a name. While the
server's response is nearly instantaneous, this also causes a lot of HTTP requests
resulting in a lot of server load.
Browsers that do not support AJAX will not display this information, which does not matter at all, because the validation can also be done when the user submits the form.
Congratulations! If you came this far, you now understand AJAX. By the way, replacing a <div> using HTML generated from a script is the most common way to use AJAX. Other possibilities include serializing the data as JSON, which is basically an object in JavaScript notation, which can then just be eval()'ed. The advantage here is that the data can be further manipulated in JavaScript.
5. 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.
Last modified on 07.03.2008 at 22:37 GMT
