Ajax for Beginners


JavaScript has had the XMLHttpRequest object for almost a decade now, but it really only started getting wide attention in 2004. All this attention was mostly due to some showoff web applications that made every developer who saw them think, “I want my site to do that!” But it also has to do with the spiffy, spiffy name given to it by the folks at AdaptivePath, who named this asynchronized application Ajax. Maybe you’ve heard of it?

A few high-profile Google applications in particular made a splash with Ajax: Maps and Gmail were first. It also powers some of the core functionality in the user interface of the ever-so-popular photo sharing siteFlickr. By now, Ajax has become integral to the fabric of the web, especially in the era of real-time applications like Twitter, Buzz and Wave (all of which use Ajax extensively in their webapp front ends, for the record). Ajax may also lay claim to being the first JavaScript object with its own fan website. Date.com doesn’t count, although I did have a scintillating chat with a lady there once about the getTimeZoneoffset method.


What is Ajax?

So what is this fancy object that everybody wants a piece of? In brief, it’s a solution to one of the big annoyances of web interfaces. Generally, the user inputs some data or makes a choice, and clicks a button that sends the data to the server. The server takes a look at the data and sends back a whole new web page, which is loaded into the browser. Reloading a page every time you want to do something is annoying, disjunctive and time-consuming for the user. XMLHttpRequest moves that browser-server interaction to behind the scenes, so the user can just keep on playing with the same page, even while elements on the page are talking to the server! Go take a look at Google Suggest if I’ve lost you — it’s a nice, eloquent example of this.

JavaScript has always been able to sneakily trigger a server-side script without anything happening in the browser by using a few classic tricks. This one, for example:onSubmit='runascript = new Image(); runascript.src="http://www.wired.com/images/archiveyscript.php?" + this.value'. That sort of chicanery is good, maybe, for caching form data to a file on the server, but it doesn’t return any information to the JavaScript that calls it, so its usefulness is limited. Ajax, on the other hand, can get a full parcel of data back from the script it calls. Hence the “XML” part of the name – which really is just there for looks, kind of like the “Java” part of JavaScript, because the returned data can be plain text or whatever you like, if XML is overkill or just not your cup of tea.

This opens up millions of exciting possibilities. Every form submission, every JavaScript event, and heaven knows what else, can now interact with server-side databases and processing power. Data retrieval, password authentication, image generation – you name it, Ajax can trigger it.


Making Your Own

The potential of Ajax-enhanced web apps is limited only by your imagination – and by browser support. Mozilla-based browsers can do it, and Safari, and newer versions of Explorer, and Opera 8 but not Opera 7. It’s best to incorporate a fallback way of doing things for users who aren’t as cutting edge as you’d like them to be. Also, Explorer does things somewhat differently (of course) from all the other browsers, so it’s necessary to fork the code to account for the irritating little 80-odd percent of the population who use IE.

Let’s build a simple application that accepts input from the user, passes it to some PHP on the server that checks it against a database, and returns the result to the browser. It comes in three parts. First, we need an HTML form. This you’ve seen before:

01 <html>
03  <head>
05  <title>Report</title>
07  <script type='text/javascript' src='xhr.js'></script> </head> <body> <form action="fallbackpage.php" method="post">
11  <p>Welcome, student. Please enter your essay here:<textarea name="essay"id="essay">
13  </textarea> <input type="submit" name="submit" value="Submit" onClick="return
15  grade(this.form.essay.value);">
17  </p>
19  </form>
21  </body>
25  </html>

Note that, for users without support for our script (named xhr.js), the form will just submit to the fallback page at fallbackpage.php.

Next comes the JavaScript. This is the exciting part, so we’ll take it slow.

1 function grade(essay) {

First, we initialize the object. We have to do it two ways, for different browsers.

01 // Mozilla version
03 if (window.XMLHttpRequest) {
05     xhr = new XMLHttpRequest();
07 }
09 // IE version
11 else if (window.ActiveXObject) {
13     xhr = new ActiveXObject("Microsoft.XMLHTTP");
15 }

Then, we escape the user input to make it URL-safe:

1 essay=encodeURIComponent(essay);

and use the open method of the object to open a connection to the PHP script:

1 xhr.open("POST","grade.php");

The method requires two arguments:first, the HTTP method (GET or POST); second, the URL of the script.

A quick HTTP header prepares the script for what it’s getting, and then the send method transmits the actual request:

1 xhr.setRequestHeader(
3      'Content-Type',
5      'application/x-www-form-urlencoded; charset=UTF-8'); xhr.send(essay);

This last step isn’t necessary for GET requests, wherein all the data can be contained in the query string of the URL.


Getting Results

Now we’re ready to see if the HTTP request worked. The readyState property counts up from zero during the request, and shows 4 when the server page has loaded successfully.

1 xhr.onreadystatechange=function() {
3      if (xhr.readyState==4) {

If the request worked, then we can get the output of the server-side script by querying the responseTextproperty, which contains a string. For more complex server script output, a responseXML property, which can hold a full document object of XML data, is also available.

1      grade = xhr.responseText;
3      alert ("Nice essay. Your grade is " + grade);
5    }
7    return false;
9 }

Want to see all that in a pastable block? Here it is in a separate file.

Finally, the third component is the PHP script, which lives on the server and waits patiently for the JavaScript to pass it some juicy data. This example uses PHP, but any language you like — Ruby, Perl, C, ASP — can do as well. The core of this example script is a natural-language function calledgrade_essay() that grades student essays from 1 to 100, but I will redact that part to conserve space.

01 <?php
03 function grade_essay($essay) {
05      return strlen($essay);
07 }
09 $essay = urldecode(implode(file('php://input')));
11 $grade = grade_essay($essay);
13 echo $grade;
15 ?>

The php://input grabs the POST data, which gets put into a string, decoded and passed to the ingenious grading algorithm. The algorithm returns a numeric grade. Lastly, we just output the grade with echo – ordinarily, this would display in the browser, but since the PHP script is running “behind the scenes,” the string output is simply returned to the JavaScript that called it. If you need structured data, an XML document would be output with an echo statement in just the same way, but the content-type of the output page must be set to text/xml.

What the user sees is this:She types her essay into the text area in the browser, clicks Submit, and within instants an alert box pops up giving her a final grade on the essay. Invisibly, the essay has been sent to the server, read and evaluated by a team of PHP gnomes, and returned with a grade, without ever reloading the page. The user can modify her essay and resubmit it endlessly.

And that’s the gist of the almost magical XMLHttpRequest object! The example is simple, but the uses of the object can be elaborately, multifariously clever. If you need further inspiration and edification, a burgeoning number of examples are dotted around the Web:

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>