AJAX In A Glance

Sunday, June 15, 2008

You can find a bunch of definition and AJAX howtos through google, I'm just adding up with this simple and quick of what, how, and why should you use AJAX in your web application.

The heart of AJAX is XMLHttpRequest object. It's supported by all AJAX-enabled browser natively, except in IE before version 7 you need to use the ActiveX object. Therefore, while in other AJAX-enabled browser we use
XMLHttp = newXMLHttpRequest();
in IE version 6 and earlier we use
> XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
And so the best approach to create the object in cross-browser application is by using try... catch to instantiate the native object first, and then the activeX version, simply like this

>
function getXMLHttp() {
var XMLHttp = null;
if (window.XMLHttpRequest) {
 try {
   XMLHttp = new XMLHttpRequest();
 } catch (e) { }
} else if (window.ActiveXObject) {
 try {
   XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
   try {
     XMLHttp = new ActiveXObject(
       "Microsoft.XMLHTTP");
   } catch (e) { }
 }
}
return XMLHttp;
}

And here's how you use it, take a look at how AJAX send a GET method
<script language="JavaScript" type="text/javascript">

function getXMLHttp() {
var XMLHttp = null;
if (window.XMLHttpRequest) {
 try {
   XMLHttp = new XMLHttpRequest();
 } catch (e) { }
} else if (window.ActiveXObject) {
 try {
   XMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
   try {
     XMLHttp = new ActiveXObject(
       "Microsoft.XMLHTTP");
   } catch (e) { }
 }
}
return XMLHttp;
}

var XMLHttp = getXMLHttp();
XMLHttp.open("GET", "somefile.php");
XMLHttp.onreadystatechange = function () {
if (XMLHttp.readyState == 4) {
  window.alert("Returned data: "+XMLHttp.responseText);
}
else
//here's where you put your loading message.
}

XMLHttp.send(null);

</script>

The above code is just a simply do a GET method from file somefile.php and show the value on javascript alert. Without having to reload the whole page, you just send the request using XMLHttp.send and get the returned data from XMLHttp.responseText.

The XMLHttp.readystate==4 means that the request had been done, the complete state is:
0-Uninitialized
1-Loading
2-Loaded
3-Waiting
4-Complete
I won't go deeper, for the complete reference of AJAX I recommend http://www.w3schools.com, it's just a glance afterall.

Hope this helps.

0 comments: