Sunday, May 3, 2009

The Core of AJAX: Part II

There are three (3) fundamental pieces to Ajax. The first piece is creating an object that most browsers can communicate with. Here is an example:

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// If IE7, Mozilla, Safari, etc: Use native object
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
// ...otherwise, use the ActiveX control for IE5.x and IE6
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}

return xmlHttp;
}

This code uses deductive logic in implementing the correct object. If the object does not throw an error, then it is most likely suitable for the browser being used. Now that we have an object, we use it to update fields or images on a web page without having to refresh the entire page. To do this, requires the second piece which is a JavaScript function call something like this:

function updateCityState()
{
http = GetXmlHttpObject();
var zipValue = document.getElementById("zip").value;
var url = "City_State.php";
http.open("GET", url + escape(zipValue), true);
http.onreadystatechange = handleHttpResponse;
http.send();
}

You can tell by the previous function that it is used to populate the City and State fields by using the Zip Code the user typed into the Zip field. That is passed to a url that does the heavy lifting and returns the data it is looking for. In this case, that would be the city and state that matches the zip code passed. The third piece is the one that extracts the data and puts it where it is needed. It would look something like this:

function handleHttpResponse()
{
if (http.readyState == 4) {
results = http.responseText.split(',');
var city = results[0];
var state = results[1];
document.getElementById("city").value = city;
document.getElementById("state").value = state;
}
}

And that is Ajax in a nutshell. Of course, there are many more things that can be done in very creative ways, but underneath it all will be these three (3) basic pieces.

1 comment:

skotandchristi said...

WHAT?!?!?!?!
Ha! You know that I have no clue what this gibberish is, but I just wanted to make a comment. :) -christi