Friday, June 01, 2007

AJAX SAMPLE

In simple terms Ajax, is plain old JavaScript, with the

ability to do asynchronous http requests, this requests are mainly XML (therefore
the name Asynchronous JavaScript and XML), however we can user the XMLHttpRequest object to get virtually any kind of document.

The JavaScript communicates with the web server

independently of the rest of the page (Asynchronously) allowing the us to get or
modify only small portion of the page making it faster and more efficient than
bringing the whole thing again every time the user changes something.

The first thing to do is to create the

XMLHttpRequest object, there are some different between who IE and other
browsers do this, so you need to validate the user's current browser



function getXMLHTTPObject()
{
try
{
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try{req = new ActiveXObject("Microsoft.XMLHTTP");}
catch(e2) { req = null;}
}
if(!req && typeof XMLHttpRequest != "undefined")
{ req = new XMLHttpRequest(); }
return req;
}

Then you create the a function that uses the object to
make a request, this function will be the one you call on your HTML, for example
when the users clicks a button or changes a form field.

The first thing is to get the object,

XmlHttp= getXMLHTTPObject();

After that, you define what you want to do after the

request has been made, usually you will call a JavaScript function to receive
the response and then change your page accordingly

XmlHttp.onreadystatechange="doSomething"

Then, you define the request, for example, you can call a

java servlet that will return the new html depending in a parameter, you can
pretty much call anything here as long as it returns either HTML (text) , or XML

You can do your request either through GET or POST with

GET, you can pass the paramenters in the URL of the request:

XmlHttp.open("GET","/apps/getContent.jsp?param2=123&param2=ABC"
,true);
XmlHttp.send(null);

Or you can use POST, for this you need to define the header of the request and the values:

XmlHttp.open("POST", "/apps/getContent.jsp",true);
XmlHttp.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");

XmlHttp.send("param2=123&param2=ABC");

After the request has been made, and a we have response, it's up to normal JavaScript to do the modifications to the HTML DOM of the page, a pretty common technique is to use the innerHTML property on DIV elements, you use XmlHttp.readyState and XmlHttp.status to know when the request has been finalized (readyStae=4) and to get the HTTP response code (success=200)

function doSomething()
{
if (XmlHttp.readyState == 4 &&
(XmlHttp.status==200 || XmlHttp.status ==0))
{
document.getElementById("div_changing").innerHTML = XmlHttp.responseText;
}
}

Here is a full sample (4 files)

region1.txt

|jsmith, John Smith|pperez, Pedro Perez|JDoe, Joe Doe

region2.txt

|jblack, John Black|jmorrison, Jim Morrison|fsinatra,
Frank Sinatra

view_divcontent.html

<h2>Changed Div Content</h2>

sample.html

<html>
<body>
<script language = "Javascript">
var XmlHttp=null;
function getXMLHTTPObject()
{
try
{
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try{req = new ActiveXObject("Microsoft.XMLHTTP");}


catch(e2) { req = null;}

}


if(!req && typeof XMLHttpRequest != "undefined")


{ req = new XMLHttpRequest(); }


return req;


}


function getSalesReps(region)


{


XmlHttp= getXMLHTTPObject();


if(XmlHttp)


{


try
{


var directory = ""+document.location;


directory = directory.substr(0, directory.lastIndexOf('/'));


XmlHttp.onreadystatechange = fillSalesRep;


XmlHttp.open("GET",directory+"/"+region,true);


XmlHttp.send(null);


}


catch(e)


{


alert(e);


}


}


}


function getApprovers()


{


XmlHttp= getXMLHTTPObject();


if(XmlHttp)


{


XmlHttp.onreadystatechange = updateApprovers;


XmlHttp.open("POST", "view_divcontent.html",true);


XmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");


XmlHttp.send(getquerystring());


}


}




function updateApprovers()


{


if (XmlHttp.readyState == 4 && (XmlHttp.status==200 || XmlHttp.status == 0))


{


document.getElementById("div_approvers").innerHTML = XmlHttp.responseText;


}


}


function getquerystring()
{


var form = document.forms["sp_req"];


var word = form.p_region_id.value;


qstr = "p_region_id=" + form.p_region_id.value;


qstr = qstr+"&p_category_id=" + "aslkhd";


return qstr;


}


function fillSalesRep()


{


var rep_select = document.forms["sp_req"].elements["p_sales_rep"];


if (XmlHttp.readyState == 4)


{


if (XmlHttp.status == 200 || XmlHttp.status == 0)


{


var response = XmlHttp.responseText;


var reps = response.split("|");


rep_select.length = 1;


rep_select.length = reps.length;




for (o=1; o < reps.length; o++)


{


var name = reps[o].split(",");


rep_select[o].text = name[1];


rep_select[o].value = name[0];


}


}


else


{


alert("Error populating Sales rep. \nStatus="+XmlHttp.status);


}


getApprovers();


}


}


</script>


<form name="sp_req">


<table>


<tr>


<td bgcolor="#EEEEDD" align="right"><b>Region: </font></b></td>


<td width="40%">


<select class="selectbox" name="p_region_id" onchange="javascript:getSalesReps(this.value);">


<option value=""> </option>


<option value="region1.txt">Region 1</option>


<option value="region2.txt">Region 2</option>


</select>


</td>


<td align="right" bgcolor="#EEEEDD" width="10%"><b>Account Rep/Manager:
</b></td>


<td width="40%">


<select class="selectbox" name="p_sales_rep">


<option value=""></option>


</select>


</td>


</tr>


</table>

</form>


<div id="div_approvers">Initial Content</div>

</body>

</html>

No comments: