A simple AJAX tutorial

AJAX powered webpages have an edge when response time and resource usage is the matter of concern. AJAX shows quick results within a blink of an eye. And the best part is user never gets to see the whole page refreshed again for simple responses.

Lets create a simple AJAX implemented webpage. and see how it works.

Create an HTML file named ajax.html. Put the following code in it.

<html>
<head>
<script>

function submitForm(url, str)
{
 var xmlhttp;
 xmlhttp=GetXmlHttpObject();
 if (xmlhttp==null)
 {
   alert ("Your browser does not support XMLHTTP!");
   return;
 }
 url=url+"?"+str;
 url=url+"&sid="+Math.random();   //to prevent the server from using a cached file
 xmlhttp.onreadystatechange=function() {
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
 {
    document.getElementById('fruitresult').innerHTML = xmlhttp.responseText;
 }

 xmlhttp.open("GET",url,true);
 xmlhttp.send(null);
}

function GetXmlHttpObject()
{
/*
 try {  xhr = new ActiveXObject('Msxml2.XMLHTTP');   }
 catch (e)
 {
   try {   xhr = new ActiveXObject('Microsoft.XMLHTTP');    }
   catch (e2)
   {
     try {  xhr = new XMLHttpRequest();     }
     catch (e3) {  xhr = false;   }
   }
 }
*/
if (window.XMLHttpRequest)     // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();

if (window.ActiveXObject)     // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");

  return null;
}
</script>
</head>

<body>
<div id="fruitresult"></div>
<FORM method="POST" name="ajax" action="">
<INPUT type="BUTTON" value="Submit"  ONCLICK="submitForm('script.php','fruit=1'); return false;">
</FORM>
</body>
</html>

Create a PHP file and save in the same directory where ajax.html is placed. Name this PHP script script.php (if you change the name you’ll have to change it in the submitForm function also)

<?php
$fruits = Array(1=>"Apple", 2=>"Banan", 3=>"Orange");
if(isset($_REQUEST['fruit']))
  echo $fruits[$_REQUEST['fruit']];
else
  echo "Sorry";
?>

Note: I have used an anonymous function in onreadystatechange event and created my xmlhttp object local (not global).
This is relly important as you might have problems in case you have made multiple calls to the same ajax file from a single HTML page.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>