Tuesday, December 21, 2010

Simple AJAX Example

AJAX = Asynchronous JavaScript and XML.

AJAX is the art of exchanging data with a server, and update parts of a web page - without reloading the whole page. ie Within the same web page we can communicate with other web page without getting out of current page.

Lets see a simple AJAX Example using .html files, directly you can run this example no need of any server.

Here we have a MainPage.html, as the name suggest this is our Main Page which will communicate with another simple page called SimplePage.html. MainPage.html will fetch data from SimplePage.html and display it without refreshing the whole page. lets see the codes.


<!-- MainPage.html -->
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>MainPage.html</title>
<script TYPE="text/javascript" LANGUAGE="JavaScript">

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

function stateChanged()
{
// if request finished and response is ready
if (xmlHttp.readyState==4)
{
//get the response data as a string
var response = xmlHttp.responseText;

alert("Response :: "+response);

document.getElementById("myDiv").innerHTML=response;
}
}

function AJAXTest()
{
document.getElementById("myDiv").innerHTML="Fetching data...";

alert("AJAXTest function called");

xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}

//Stores a function (or the name of a function) to be called automatically each time the readyState property changes
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET","SimplePage.html",true);
xmlHttp.send();
}

</script>
</head>

<body>
This is a Main page. <br/><br/>
<a href="#" onclick="AJAXTest()">Click Here</a> to call SimplePage.html<br/><br/>

<div id="myDiv"> </div>

</body>
</html>



Add a simple text line in another page, which will be displayed on main page.

<!-- SimplePage.html -->


<h1>This is a Simple Page</h1>



Output