Home » AJAX » Basic Tutorials For AJAX

Basic Tutorials For AJAX


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 11 other followers


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:

 <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

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:


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


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:

      '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.

 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:



  1. 1st of all iphone has bttr graphics n wtf ur runnin
    two devices on exactly the same wifi ofcourse one particular of them is gnna hv the benefit .
    .. Check out the other videos iphone gave s2 a 3 secnd headstart n still beat it
    n bigger screen is really a disadvantage trigger u cant hold the
    dam factor in 1 hand n use it btw it looks so stupi … Iphone 3gs evn looks bttr den dat peice of trash .
    .. Iphone all d wayy

  2. Awesome issues here. I’m very happy to see your post. Thanks so much and I am having a look forward to touch you. Will you please drop me a e-mail?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: