Getting started with AJAX

This guide provides some background info on Ajax, and then jumps right in and gets you started with examples.

JavaScript has been the main use for XMLHttpRequest objects for a good number of years now, but only recently did it start to gain some “fame”. A lot of the ruckus has to do with the many advanced web applications having web developers that see it, drool and want their own site to have those same exact advanced applications/features. But some of it also has to do with the group of people at AdaptivePath who have named this application Ajax

Ajax Beginners: What in the world is Ajax?

In a nutshell? Well Ajax is a solution to web interfaces.

Commonly, the web user enters some data or makes a simple choice, and clicks a button finalizing that choice or data entry and sends the data over to the server. The server hastily observes the data and sends back an entire new web page. Having to reload a page every time you want to do something is very annoying, disjunctive and extremely time-consuming for the user. XMLHttpRequest resurfaces the 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!

With JavaScript we’ve always been able to server-side script without anything happening in the browser by using a few classic tricks up our sleeves.

Caching form data to a file with JavaScript on a server is good, but this usually doesn’t return any useful information to the JavaScript that calls it, so its effectiveness is very limited. Ajax, however, 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 of sorts, kind of like the “Java” part of JavaScript, because the returned data can be plain text or whatever you like, if XML isn’t your preferred choice.

This alone opens up so many exciting possibilities. Every form submission, every JavaScript event, and whatever else application, can now interact with server-side databases and processing power! Data retrieval, password authentication, image generation – you just name it, Ajax can activate it.

Putting Ajax Into Practice

The only thing that limits Ajax-enhanced web application is your imagination and by browser support. Mozilla-based browsers can do it, Safari, and newer versions of Internet Explorer, and Opera 8 but not Opera 7. It’s best to slot in an alternative way of doing things for users who aren’t as witty as you’d hope for them to be. Also, Internet Explorer does things somewhat differently (most definitely) from all the other browsers, so it’s pretty essential to work the code to account for the irksome 80% of the population who rely on Explorer.

Now to the exciting part! Let’s generate a straightforward application that can accept 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 in use. We assimilate it in three parts.

First, we need an HTML form. As you’ can see below:

<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: For users without proper support for our script (named xhr.js), the form will just simply submit to the fallback page at fallbackpage.php. Ok, this is where the JavaScript comes in, we’ll take it slow.

function grade(essay) {

The first thing we have to do is initialize the object. There are two ways we must do this, for different browsers.

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

We then escape the user input to make it URL-safe:

    essay=encodeURIComponent(essay);

and use the open method of the object to open a new 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 asserts the script for what it’s getting, and then the send method conveys 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.

Obtaining Final Results

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

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

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

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

In conclusion, the third component consist of PHP script, which basically lives on the server and waits patiently for the JavaScript to pass it some juicy data so it can thrive. This example uses some PHP, but any language you like — Ruby, Perl, C, ASP — can address your needs 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 clever 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 basically must be set to text/xml.

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

And that’s the general substance of the almost magical XMLHttpRequest object! The example is pretty simple and straight forward, but the uses of the object can be highly, multi clever.

For further inspiration and great examples of ingenious Ajax applications you can momentarily steer away from SimpleHelp.Net and visit iGoogle, Pageflakes, Netflix and Netvibes.


However, the data and functions that Ajax sends and acts out is simply up to you.

{ 1 comment… add one }
  • noyelle January 1, 2009, 11:01 pm

    Qui a fait le texte en français ?……

    french or chinese translation ?…..

Leave a Comment