Tuesday, October 27, 2009

Understanding AJAX


AJAX is a technique rather than a technology: It describes how JavaScript can be used to pull data from the server using the XML HTTP Request object and then insert this data into the website using DOM. This is done asynchronously - that is, in the background, without having to refresh the whole page. The technology which AJAX is based on has already been available for a while, the combination is what makes it new.You can try the examples online or download them and run them locally (except for the PHP script, that would require a webserver with PHP).Simple (html)example shows how to set the content of the


<script type="text/javascript">
function replace() {
 document.getElementById('foo').innerHTML = "Hello, <b>AJAX</b>world!";
}
</script>


<p><a href="javascript:replace()">ReplaceText</a></p>


<div id="foo">
  Hello, world!

The XML HTTP Request objectThe XML HTTP Request object is used to make HTTP requests. This is the core object that is reqd for doing an AJAX call.

Simple script which shows the required steps for doing an AJAX call.

<script type="text/javascript">
var http = false;


if(navigator.appName == "Microsoft Internet Explorer") {
  http = newActiveXObject("Microsoft.XMLHTTP");
} else {
  http = newXMLHttpRequest();
}


http.open("GET", "test.txt");
http.onreadystatechange=function() {
  if(http.readyState == 4) {
   alert(http.responseText);
  }
}
http.send(null);
</script>

Combining the Simple Html example with the XMLHttpRequest (above script) gives us AJAX

<script type="text/javascript">
var http = false;


if(navigator.appName == "Microsoft Internet Explorer") {
  http = newActiveXObject("Microsoft.XMLHTTP");
} else {
  http = newXMLHttpRequest();
}


function replace() {
  http.open("GET","test.txt", true);
 http.onreadystatechange=function() {
    if(http.readyState == 4){
     document.getElementById('foo').innerHTML = http.responseText;
    }
  }
  http.send(null);
}
</script>


<p><a href="javascript:replace()">ReplaceText</a></p>


<div id="foo">
  Hello, world!
</div>

While the previous example fully demonstrated AJAX, it was totally boring. Including the contents of a static file into the page could have been done much easier, you might say. However, AJAX becomes powerful when combined with a server-sided script. Consider the following PHP script, which validates a user name entered into a form. The name chosen has to be at least three letters long and must still be available:

<?php
function validate($name) {
  if($name == '') {
    return '';
  }
 
  if(strlen($name) < 3) {
    return "<span id=\"warn\">Username too short</span>\n";
  }
 
  switch($name) {
    case 'bob':
    case 'jim':
    case 'joe':
    case 'carol':
      return "<span id=\"warn\">Username already taken</span>\n";
  }
 
  return "<span id=\"notice\">Username ok!</span>\n";
}
 
echo validate(trim($_REQUEST['name']));
?>

Simple html page, which makes the call to the PHP code….

<script type="text/javascript">
var http = false;
 
if(navigator.appName == "Microsoft Internet Explorer") {
  http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  http = new XMLHttpRequest();
}
 
function validate(user) {
  http.abort();
  http.open("GET", "validate.php?name=" + user, true);
  http.onreadystatechange=function() {
    if(http.readyState == 4) {
      document.getElementById('foo').innerHTML = http.responseText;
    }
  }
  http.send(null);
}
</script>
 
<h1>Please choose your username:</h1>
 
<form>
  <input type="text" onkeyup="validate(this.value)" />
  <div id="foo"></div>
</form>

Now enter a name into the text field. Try bob, jim, joe orcarol. The <div> will update as you type, giving you information onwhether your username is valid. Also note the http.abort();, which will abort theprevious request, if a new one comes in. This is useful when the user typesvery quickly. The script could probably improved by waiting a couple of secondsafter the user has typed a name. While the server's response is nearlyinstantaneous, this also causes a lot of HTTP requests resulting in a lot ofserver load.
Browsers that do not support AJAX will not display this information, whichdoes not matter at all, because the validation can also be done when the usersubmits the form.
Congratulations! If you came this far, you now understand AJAX. By the way,replacing a <div> using HTML generated from a script is the most commonway to use AJAX.Other possibilities include serializing the data asJSON, which isbasically an object in JavaScript notation, which can then just be eval()'ed. The advantage here is that the data can befurther manipulated in JavaScript.

Imp: We can also use other Server side scripting language likeJava Servlets / .net.. instead of the PHP.

Stumble
Delicious
Technorati
Twitter

0 Comments:

Post a Comment