Top » AJAX » SMALL EXAMPLE If you find this page useful
please make a secure donation
My Account  |  Cart Contents  |  Checkout   

Small Example

If we take a look at a small form with two items or components like this one:

<form name="testform">
ONE: <input type="text" onkeypress="ajaxRun()" name="one" >
TWO: <input type="text" name="two" >
</form>
Take interest that we did not put a SUBMIT on this form.
Also note that we added an onkeypress event to run a function. So each time a key is pressed inside the focus of the first form-text box we will run our function.

Now we will add in that function. It will first attempt to determine which browser a person has, so we know which version of the AJAX HTTP header object to use:
<script>
function ajaxRun()
{
  var xmlHttp;
  try
  {
    /* Firefox, Opera 8.0+, Safari */
    xmlHttp=new XMLHttpRequest();
  }
  catch (e)
  {
    /* newer IE */
    try
    {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      /* older IE */
      try
      {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        alert("Your browser is old and does not have AJAX support!");
        return false;
      }
    }
  }
}
</script>

Now we need to detect when the HTTP header object used in AJAX changes. There are 5 states:
  • 0 - Not Initiaized Yet
  • 1 - Object Configured
  • 2 - Request Sent
  • 3 - Request in Progress
  • 4 - Request Complete

Now we can respond to new data from the server:
xmlHttp.onreadystatechange=function()
{
  if(xmlHttp.readyState==4)
  {
    document.testform.two.value=xmlHttp.responseText;
  }
}

Next we need to send a request so we can process the response:
    xmlHttp.open("GET","test_ajax.php",true);
    xmlHttp.send(null);

Now the only thing left is to write some server code (in test_ajax.php). Since it only needs the data for field two, we will return a random number.
NOTE: This is PHP code which goes in a separate file from the HTML/JAVASCRIPT/AJAX file we were previously describing.
<?
echo rand();
?>

Click here to see the example run