Tweet
Here is the code.
<html>
<head>
<title>An AJAX DEMO</title>
<script language="javaScript">
var XMLHttpRequestObject=false;
if(window.XMLHttpRequest)
{
XMLHttpRequestObject=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
XMLHttpRequestObject=new ActiveXObject("Micosoft.XMLHTTP");
}
function getData(dataSource,divID)
{
if(XMLHttpRequestObject)
{
var obj=document.getElementById(divID);
XMLHttpRequestObject.open("GET",dataSource);
XMLHttpRequestObject.onreadystatechange=function()
{
if(XMLHttpRequestObject.readyState==4 && XMLHttpRequestObject.status==200)
{
obj.innerHTML=XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<h3>An Ajax Demo</h3>
<form>
<input type="button" value="Retrieve message from txt file" onclick="getData('data.txt','targetDiv')">
</form>
<div id="targetDiv">
<p>The retrieved message will appear here</p>
</div>
</body>
</html>
Before clicking the button :
After clicking the button :
This simple program just fetches the contents of a text file, data.txt, from the server when you click the button. The difference between this application and a normal web page is that when you click the button the page doesn't blink and redisplay - all that happens is the default text is replaced by a text from a text file which is already stored in the server.
The button is connected to a Javascript function, getData and passes two arguments to that function - "data.txt", the name of the file on the server to fetch, and "targetDiv", which is the name of the <div> element to display the downloaded text in.