Monday, September 03, 2007

AJAX with HTML

Implementation of AJAX is very simple. You can have a single HTML page and run a huge ERP from there using AJAX.

All you need to know is
HTML, JAVASCRIPT, CSS

Entire process can be categorized as following....



Step 1. Send AJAX request to some server side page
Step 2. Sniff for response
Step 3. Show the response text

If you get into the implementation that these 3 steps are very easy to understand. Here's the explanation....

Step 1:

Create XMLHttpRequest Object. Now the catch here is that different browsers handle this thing differently. So use the following code that will help everywhere...


function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
// Internet Explorer 6.0 +
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
// Internet Explorer 5.0 +
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
}





Now we have created an object for AJAX handling. Next we will call the page that contains data to be displayed. But before that, you must understand the onreadystatechange and readyState properties of XMLHttpRequest Object.

onreadystatechange is an event that is fired whenever state of xmlHTTP object is changed. In this event, the readyState property is set to some pre-defined values like

0: The request is not initialized
1: The request has been set up
2: The request has been sent
3: The request is in process
4: The request is complete

You need to call your function when onreadtstatechange event is fired. For this, you can write

onreadystatechange = function {

if(xmlHttp.readyState==4) {

document.myForm.LBL.value=xmlHttp.responseText; }


}

All you need is a textbox called LBL, which will hold the value recieved by this object. To recieve some value, you need some server side page and call it like this...

xmlHttp.open("GET","mypage.asp",true);
xmlHttp.send(null);

Well, you are done.

Surprise!!! All three steps are complete.

Yes! You are done with the basics of AJAX. Now just to summarize, I will write same code in combined form...



function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
// Internet Explorer 6.0 +
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
// Internet Explorer 5.0 +
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
}

xmlHttp.open("GET","mypage.asp",true);
xmlHttp.send(null);

xmlHttp.onreadystatechange = function {

if(xmlHttp.readyState==4)
{
document.myForm.LBL.value=xmlHttp.responseText;
}
}




0 comments: