Pages

Friday, June 26, 2009

Getting started with Ajax: Basics.

Background:

I had used XmlHttp in my javascripts for quite long and extensively. espically dealing with grid control... but lately I come to know that it was called as an AJAX... which has much more than that... to make your UI richer. A common way of calling ajax function is to create an object of XMLHttpRequest. this you can either use it directly or can use wrapper libraries available in the market like extjs, JQuery, Prototype etc. to begin with I will present the internal coding of actual ajax code how it works. please see the following code...

Basic Code: First to check which browser we are using and accordingly activate XmlHttp object as



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;
}

It just that I have saparated code. creating of XMLHttp object in different function as above and calling it in other function as below


function getAjaxResponse(sURL){
xmlHttp = GetXmlHttpObject();
xmlHttp.onreadystatechange=stateChanged(){
if (xmlHttp.readyState==4){
document.getElementById(divID).innerHTML=xmlHttp.responseText;
};
};
xmlHttp.open("GET",sURL ,true);
xmlHttp.send(null);
}

Lets observe the code above we have specifed call back function to receive response from server.



xmlHttp.onreadystatechange=stateChanged();

... here you can either mention function name or you can inline the function itself. this function block will get executed when you receive response from server. Here actually you can do more based on the status code that you receive from server, for e.g. you can show process status while you receive response or please wait messgage/image to user till response received etc. please see the table below for the status code that you get on this function.
Response that you get from the server can be of Html code or xml or simply a string, and it depends how you want to show it to user. in above code I have shown that it returns html response which I directly paste into div block.
fire http GET/POST request to server


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

Please note the following things when calling open,

  • Always set Async to true.
  • always set call back function before calling send()
  • To send form data/POST use endcodeURI() for all data values and set mime type of request to "application/x-www-form-urlencoded"

basic advantage of using javascript to post the request to server is that we don't have to wait till server response arrives. instead we can perform other task. I am listing below the XMLHttpRequest objects method available here.


Method/ PropertyDescription.
abort()stops listining for current response.
getAllResponseHeader()Get array of response header as key value pair.
getRespoonseHeader(name)Get response header by name passed as key.
open(method, url[,asyncFlag[, "username"[, "password"]]])

This prepares the xmlHTTPRequest object to make call to the server.
Method: HTTP; can be either GET, PUT or POST.
url: is url string to open can be either obsolute or relate may include querystring

send(content)

perform http request.
content: string to be used as request body, i.e. to form POST body, you can format your POST parameters just like querystring.

setRequestHeader(header, value) Add header to Http requset, normally a key value pair and mostly used to set content type of request.
onreadystatechangeused to set as callback fucntion that handles request state change.(similar to onclick, onload)
readyState

returns the status of the request which can be on of following at a time
0:= uninitialised
1:= loading
2:= loaded
3:= interactive
4:= complete

responseTextreturns server response as String
ResponseXMLreturns server response as XML Document
statusreturns HTTP status code like 200 for OK etc
statusTextreturn String representation of HTTP status code like OK for 200, not found for 404 etc.

In above example I have already shown how I am getting HTML response from server which I am setting back to perticlular html object. see below the example of parsing xml response received from server and setting to html object.
here I assume that I am getting some key-value pair from server as xml response which i need to set to combobox in html so I am passing combobox object to method

xmlHttp.onreadystatechange=usrfunc;
....
....
function processListXML(xmlId, objlist ){
// first remove all existing option values from list box
for(i=objlist.options.length-1;i>=0;i—){
objlist.remove(i);
}
var t = document.getElementById(xmlId);
var tableData = t.getElementsByTagName("RList");
if(tableData != null){
var t = tableData.item(0);
var columns = t.getElementsByTagName("ROption");
if(columns != null){
for (j = 0; j < columns.length; j++){
key= columns[j].getAttribute("id");
value= columns[j].firstChild.data;
objlist.add(new Option( value ,key ));
}
}
}
}


Now assume that I get following xml
<RList>
<ROption id="01">INDIA </ROption>
<ROption id="02">JAPAN </ROption>
<ROption id="03">AMERICA </ROption>
</RList>

No comments:

Post a Comment