Add this blog to Del.icio.us, Digg or Furl | Create Watchlist for this blog

ajax script tutorial - quick technology intro

I love short stories to get started in a new technology. So here is one about ajax - the current hype on web platforms.

What is it for

Send requests asynchronous to your webserver and process the results within the current client-page-DOM without re-loading the whole page!

If you need special data in your webpage as response to a user action then use ajax. It is not meant for a whole Web GUI. If you use ajax for too much user navigation you will explore the two major drawbacks soon: The user can’t use the browser’s back button and search engines will ignore you (well, there are workarounds but those are bad browser dependent hacks).
The typical situation where ajax is useful is when you have two drop-down lists and the content of the second list depends on the selected entry of the first. I.e. “choose your cpu:” - first list contains manufacturers “Intel”, “AMD”, “IBM”, “Motorola”, second list contains processor model.

Technology, Syntax, Objects

On client side your users need a javascript enabled webbrowser of a “newer” generation. On server side you need nothing special, just use your favorite technique (there’s more importance on the selected protocol format - like just string or xml or json). On webdesigner’s side you need some DHTML and javascript.

A typical javascript function that initiates an ajax call with an url as parameter looks like this:

var request = false;  // you need this variable globally 

function initiateAjaxCall(url)
{
  request  = new XMLHttpRequest();
  request.open("get", url, true);
  request.onreadystatechange = async_event;
  request.send(NULL);
}

Where the XMLHttpRequest is the javascript-ajax object to focus on (for IE6 you need some workarounds well known in the web). ajax is “Asynchronous Javascript and XML” so it’s asynchronous and so you need a callback function (a function that gets called when an event occurs). Above “async_event” is declared to be your event handling function to handle the webserver’s asynchronous response.

There are four events your callback will be called with:

ajax state table:

0 = uninitialized
1 = loading
2 = loaded
3 = interactiv
4 = complete

For this quick intro, only state 4 is of interest. Maybe I’ll get back on this later in another post (can program nice progress bars with this infos).
Your event handler could look like this:

function async_event() {
  switch(request.readyState) {
  case 4:
    if (request.status != 200) {
      alert("HTTP Response not OK : Code:"+request.status);
    } else {
      myProcessing(request.responseText);
    }
  break;
  default:  break;
  }
}

In the “myProcessing” function the final response processing is done (usualy it’s any DHTML manipulation of the current DOM).

Full Code Example
It’s not that easy to invent a simple example that makes at least little sense, so don’t be to critical with this.

ajax script tutorial - example 1
Initial view of the example

To show up the technology in short code we build a website that displays the current client time (javascript) and a button to request the current server time. When the button is pressed, the current server time get’s fetched from the server by magical AJAX and is finally display via a DOM manipulation in - again - javascript.

We start with the server side (in php - to keep it simple)
File getTime.php

<?php echo date("H:i:s"); ?>

That was pretty simple, now we do the html page that uses ajax:
File getTime.html


<html>
<head><title>AJAX Test 1</title>
<script type="text/javascript">
   <!--
   // our global request variable
   var request = false; 

   // function to initiate the ajax call
   function initiateAjaxCall(url)
   {
     request  = new XMLHttpRequest();
     request.open("get", url, true);
     request.onreadystatechange = async_event;
     request.send(null);
   }

   // ajax callback function
   function async_event() {
     switch(request.readyState) {
     case 4:
       if (request.status != 200) {
         myProc("Error Response Code: "+request.status);
       } else {
         myProc(request.responseText);
       }
     break;
     default:  break;
     }
   }

   // function to print the ajax result
   function myProc(text) {
      var now = new Date();
      var ct = document.getElementById("CTIME");
      var st = document.getElementById("STIME");
      ct.innerHTML = ""+now.getHours()+":"+
                               now.getMinutes()+":"+
                               now.getSeconds();
      st.innerHTML = text;
   }
   //-->
</script>
</head>
<body onLoad="myProc('---');">
   <h1>Ajax Test 1</h1>
   Client Time: <span id="CTIME"></span><br>
   Server Time: <span id="STIME"></span>
   <br><br>
   <input type="submit" value="fetch server time via ajax now"
                          onClick="initiateAjaxCall('getTime.php');">
</body>
</html>

ajax script tutorial - example 2
After pressing the button, server’s time is displayed

Social Bookmarking:
Add to social bookmarking sites.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • MisterWong
  • Furl
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati

And I've started a Drupal relaunch of my EDV Beratung now.

One Response to “ajax script tutorial - quick technology intro”

  1. » Started New Drupal Project - Rainer Feike techblog » Blog Archive Says:

    […] content as well as stock quotes. So I will need to look somewhat deeper to caching technology and AJAX. It will also contain community features like blogs and a forum, so there also lot’s of work […]

Leave a Reply

I appreciate all comments that add substantial content to my articles. I do not like "link-building" comments and I do not like "congratulation" comments. Every such like data posted here will go to akismet hell.