Interactive demos require Javascript. Anything else works.

Simple Ajax

posted by Stephan Brumme

Interactive Web Sites

Ajax is the technology upon which pretty much every modern interactive website is build (except for these weird Flash sites). Professional web sites use large frameworks like jQuery that wrap the details of Ajax in a nice programming interface. That's perfectly fine but total overkill for a small blog like this.

Live Demo

This DNS-to-IP resolver returns the IPv4 address of any domain. It may take up to 3 seconds to get a result.

Enter a domain name: => IP:

Have a look at the sorting algorithm live demo which is based on Ajax, too.

Barebone Ajax

Support for Windows XP is running out and that's very good news because sooner or later Internet Explorer 6 will vanish from the market. Without taking care of that old beast, Ajax becomes simple and easy.

My Ajax requests often have some parameters that I pass from the user's browser to my server encoded in the URL, e.g. ajaxsort.php?12345. On the server, a script or binary is executed which returns plain text or sometimes HTML code. This result shall be inserted somewhere in the original web page.

The whole Ajax code consists of 18 lines:
hide <script type="text/javascript"> // start an ajax request function request(domId, query) { var ajaxObject = new XMLHttpRequest(); if (!ajaxObject) return false; ajaxObject.onreadystatechange = function() { if (ajaxObject.readyState == 4 && ajaxObject.status == 200) document.getElementById(domId).innerHTML = ajaxObject.responseText; }; ajaxObject.open('GET', encodeURI(query), true); ajaxObject.send(null); return true; } </script>
When creating such an Ajax-enabled web page, I need to add an HTML element with a known ID, e.g. ajaxdemo
<span class="ajaxdemo"></span>
Then I initiate the Ajax request once a certain condition is fulfilled, e.g. a key was pressed:
<form> <input type="text" id="num" onKeyUp="request('ajaxdemo', 'ajaxsort.php?'+this.value);" /> </form>
The parameters of request are the ID, here I used ajaxdemo, and the URL (incl. parameters) of the server object generating the response.

How It Works

The Ajax communication is handled by XMLHttpRequest.
onreadystatechange contains the code executed once the response was received from the server. An unnamed function, a so-called lambda function, checks for errors (readyState 4 means completed, status 200 means valid data) and then replaces the contents of the HTML element carrying the ID domId by the server's responseText. responseText can be plain text or HTML.

But before any response arrives, we have to send the request first ;-) and that's handled by open and send.
Special characters not allowed in an URL are rewritten first (encodeURI) and the request is defined to be asynchroniuously (third parameter is true).
All data is already encoded in the URL (open used GET method / first parameter) so there is no need to send additional data. Therefore send has a null parameter.

There can be multiple pending Ajax requests. status.stephan-brumme.com frequently sends more than 30 concurrent Ajax requests.

Live Demo's Source Code

That's the input form on this page:
hide <form> <input type="text" placeholder="(enter domain name, e.g. google.com))" size="40" id="url" /> <input type="button" value="Resolve !" onclick="request('ajaxdemo', '/simple-ajax/resolve.ajax?'+document.getElementById('url').value);" /> => IP: <span id="ajaxdemo"></span> </form>
And here is the super-simple PHP script invoked by the live demo:
hide resolve.ajax <? echo gethostbyname($_SERVER["QUERY_STRING"]); ?>
Note: my Apache web server's .htaccess treats .ajax the same way as PHP files.

Internet Explorer 6

If you have to support Internet Explorer 6, you can prepend the following code (see here for more details):
hide if (typeof XMLHttpRequest == "undefined") XMLHttpRequest = function () { try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e) {} try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} return null; };
homepage