Working with AJAX

In December of 2004, a co-worker emailed me a link to the new Google Suggest beta. The term "AJAX" had not yet been invented. My reaction (I am guessing it was a similar reaction as many other Web developers around the World) was "How the heck did they do that?" I did some research and reverse-engineering to see how it ticked.

When I learn new stuff I like to break it down to the simplest possible so I can grasp the basics. Here is the shortest script I can write that grabs a server file: (To pare it down to 4 lines, I had to sacrifice it working in IE 6) It returns in an alert box the entire contents of the "test.txt" file that I made especially to test this.

function getStuffSimple() { var oXht = new XMLHttpRequest(); oXht.open("GET", "test.txt", false); oXht.send(null); alert(oXht.responseText); }

Try the getStuffSimple() function (Won't work in IE 6.)

The data is a comma-delimited string. Fortunately, even though every implementation of the object has "XML" somewhere in its name, it can return plain text or even binary data I am told. (Though technically the data is inside the body tag of an XHTML page so it is all kinda XMLish.) Anyhow, the next important step is to make it work in more browsers. The following function will return an object that should work in all modern browsers and older versions of IE:

function X$() { if (window.XMLHttpRequest) return new XMLHttpRequest(); try {return new ActiveXObject("Microsoft.XMLHTTP")} catch(e) {return new ActiveXObject("Msxml2.XMLHTTP")} }

The true power of this object lies in grabbing dynamic server-generated content without refreshing the page. The function below will return the server time (and should work in Firefox because I used the above function to create the object).

function getServerTime() { var oXht = X$(); oXht.open("GET", "time.php", false); oXht.send(null); alert(oXht.responseText) }

The time.php file looks like this:

<?=date("d-M-Y")?>

Try the getServerTime() function

The last thing I wanted to learn was how to pass information along with the request. The following code will form post to the server page.

function sendStuff() { var oXht = X$(); oXht.open("POST", "data.php", false); oXht.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); oXht.send("formdata1=246&formdata2=357"); alert(oXht.responseText); }

The data.php file looks like this:

<?php print 'data1 = ' . $_POST["formdata1"] . ' and data2 = ' . $_POST["formdata2"]; ?>

Try the sendStuff() function

I figure that expanding on the above function, I can do pretty much anything now. In my searches I also found a cool function using the XMLHTTP object to detect if a Web page exists:

function getURLState(strURL) { var oXht = X$(); oXht.open("HEAD", strURL, true); oXht.onreadystatechange = function() { if (oXht.readyState == 4) { if (oXht.status == 200) {alert("URL Exists")} else if (oXht.status == 404) {alert("URL doesn't exist")} else {alert("Status is "+oXht.status)} } } oXht.send(null); }

Does data.php Exist? (It should) ; Does xxx.html Exist? (It shouldn't)

Notice that the asynchronous flag was set to "true" this time. You don't want The function to die if it tests a non-existent URL. In fact, most XMLHTTP calls use the onreadystatechange property as above to keep the function from freezing if there is a problem with the data transfer. Read more about the asynchronous flag.

If you are still reading this, you've earned 5 Enterprises on the geek scale.