Tuesday, October 21, 2008

Simple AJAX

Make your web page optimized by implementing AJAX technology. AJAX stands for Asynchronous JavaScript and XML made popular by Google.

XMLHttpRequest object is the key behind the communication between clients and server. Different browsers use different methods to create the XMLHttpRequest object. Internet Explorer uses an ActiveXObject, while other browsers uses the built-in JavaScript object called XMLHttpRequest.

The onreadystatechange event of the XMLHttpRequest will process the response from a server. By invoking the function on this event we retrieve the information sent by the server.

The readyState property holds the status of the server's response. Each time the readyState changes, the onreadystatechange function will be executed.

Here are the possible values for the readyState property:
State Description
0 Request is not initialized
1 Request has been set up
2 Request has been sent
3 Request is in process
4 Request is complete

Here is the sample code.


start of html tag
start of body tag

start of javascript function

function simpleAjax(){
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser is very old, does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function() {
if(xmlHttp.readyState==4) {
//get data from the server
document.simpleAjax.fromServer.value=xmlHttp.responseText;
}
}
xmlHttp.open("GET","simpleAjax.php",true);
xmlHttp.send(null);
}

end of javascript function

start of form tag name="simpleAjax"

Name: between angle bracket(input type="text" onkeyup="simpleAjax()" name="user")
Data: between angle bracket(input type="text" name="fromServer")

end of form tag
end of body tag
end of html tag

php file

///output the data to the client
////echo "Data from Server";
//?>

save the form as "simpleAjax.php" in the same directory as html file.

No comments: