Feb 6, 2009

The Magic of AJAX

I just recently used AJAX for the first time and had heard a lot about it.  It is really cool.  AJAX allows one to make HTTP requests for information while a page is still loaded and can then use that information to update the webpage without ever reloading the page the visitor is viewing.  I'm sure there are many ways to do this but I have employed the following:

Here's an html page that will call a javascript to make an AJAX request
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="AJAXscript.js" language="JavaScript"></script>
    <title>My Ajax Test</title>
</head>
   
<body>
   
    <h1>This is an example script for using AJAX to process a webpage.</h1>
   
    <FORM name="ajax" method="POST" action="">
        <p>
            Click on the button below to open the remote file to get values to add to the select box below
        </p>
        <p>
            <INPUT type="BUTTON" value="Run AJAX Script"  ONCLICK="getAdditionalOptions()">
        </p>
        <p>
            AJAX Respone:
            <br/>
            <input type="text" disabled name="dyn" size="64" value="">
        </p>
    </FORM>

<hr/>


    <form name="carList" action="">
        <select name="cars">
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="fiat">Fiat</option>
            <option value="audi">Audi</option>
        </select>
    </form>


</body>

</html>
Here's the javascript file that makes the AJAX request
var xmlHttp


function GetXmlHttpObject()
{
var xmlHttp=null;
try
 {
 // Firefox, Opera 8.0+, Safari
 xmlHttp=new XMLHttpRequest();
 }
catch (e)
 {
 //Internet Explorer
 try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}

function getAdditionalOptions()
{    
    document.ajax.dyn.value = "Started...";
    xmlHttp=GetXmlHttpObject()
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request")
         return
     }   
    
    var url="data.xml"
    xmlHttp.onreadystatechange=stateChanged_updateOptions
    xmlHttp.open("GET",url,true)
    xmlHttp.send(null)
   
}

function stateChanged_updateOptions()
{
    document.ajax.dyn.value = "Wait server...";
    if(xmlHttp.readyState == 4 || xmlHttp.readyState=="complete")
    {
        if(xmlHttp.status == 200)
        {               
               
            document.ajax.dyn.value = "Received.";
            //process list of received names
            var formList = xmlHttp.responseText.split("|");
           
            //populate list with databases
            for (o=0; o < formList.length; o++)
            {
                var opt = document.createElement("option");
                // Assign text and value to Option object
                opt.value = formList[o];
                opt.text = formList[o];
                // Add an Option object to Drop Down/List Box
                document.carList.cars.options.add(opt);
            }
        }   
        else   
        {
            document.ajax.dyn.value="Error: returned status code " + xmlHttp.status + " " + xmlHttp.statusText;
        }   
    }
}
and here's the xml file that is read by an HTTP server and then returned to the javascript
Ford|GMC
While I will mention this in a future post, one can make the AJAX request to a url such as a PHP file that can process data and then return the data as a string and the javascript can process that to put into the webpage

No comments:

Post a Comment