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">
<script TYPE="text/javascript" LANGUAGE="JavaScript">

function GetXmlHttpObject()
var xmlHttp=null;
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
catch (e)
// Internet Explorer
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);


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

alert("AJAXTest function called");

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

//Stores a function (or the name of a function) to be called automatically each time the readyState property changes


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

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


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

<!-- SimplePage.html -->

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


No comments:

Post a Comment