Member Sign In
Not a member?

A Wired.com user account lets you create, edit and comment on Webmonkey articles. You will also be able to contribute to the Wired How-To Wiki and comment on news stories at Wired.com.


It's fast and free.

Sign in with OpenID
Sign In
Webmonkey is a property of Wired Digital.
processing...
Join Webmonkey

Please send me occasional e-mail updates about new features and special offers from Wired/Webmonkey.
Yes No

Please send occasional e-mail offers from Wired/Webmonkey affiliated web sites and publications, and carefully selected companies.
Yes No

I understand and agree that registration on or use of this site constitutes agreement to Webmonkey's User Agreement and Privacy Policy.
Webmonkey is a property of Wired Digital.
processing...

Retrieve Sign In

Please enter your e-mail address or username below. Your username and password will be sent to the e-mail address you provided us.

or
Webmonkey is a property of Wired Digital.
processing...

Welcome to Webmonkey

A private profile page has been created for you.
As a member of Webmonkey, you can now:
  • edit articles
  • add to the code library
  • design and write a tutorial
  • comment on any Webmonkey article
Close
Webmonkey is a property of Wired Digital.

Sign In Information Sent

An e-mail has been sent to the e-mail address registered in this account.
If you cannot find it in your in-box, please check your bulk or junk folders.
Sign In
Webmonkey is a property of Wired Digital.

Ajax for Beginners

/skill level/
/viewed/
0 Times


JavaScript has had the XMLHttpRequest object for a good number of years now, but it's really only started getting wide attention recently. All this attention is mostly due to some showoff web applications that make every developer who sees 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:Suggest, and Maps, and Gmail. It's also powers some of the core functionality in the user interface of the ever-so-popular photo sharing site Flickr. By now, Ajax has become a buzzword, and may even be 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:


<html>
 <head>
 <title>Report</title>
 <script type='text/javascript' src='xhr.js'></script> </head> <body> <form action="fallbackpage.php" method="post">
 <p>Welcome, student. Please enter your essay here:<textarea name="essay" id="essay">
 </textarea> <input type="submit" name="submit" value="Submit" onClick="return
 grade(this.form.essay.value);">
 </p>
 </form>
 </body>
 </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.

 function grade(essay) {
 

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


    // Mozilla version
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    // IE version
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
 

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

    essay=encodeURIComponent(essay);
 

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

    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:

 xhr.setRequestHeader(
      'Content-Type',
      '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.

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

If the request worked, then we can get the output of the server-side script by querying the responseText property, 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.

      grade = xhr.responseText;
      alert ("Nice essay. Your grade is " + grade);
    }
    return false;
 }
 

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 called grade_essay() that grades student essays from 1 to 100, but I will redact that part to conserve space.

 <?php
 function grade_essay($essay) {
      return strlen($essay);
 }
 $essay = urldecode(implode(file('php://input')));
 $grade = grade_essay($essay);
 echo $grade;
 ?>
 
 

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:

  • Social news site Digg


But what data you send and receive with Ajax is up to you.

  • This page was last modified 16:06, 8 May 2008.
Edit this article
Reddit Digg
 
Subscribe now

Special Offer For Webmonkey Users

WIRED magazine:
The first word on how technology is changing our world.

Subscribe for just $10 a year