Using AJAX to retrieve message from a php file

This simple program just fetches the contents of a php file, data.php , 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.

Here is the php code.

<?php
echo "Hello World !!! ";
echo " Welcome to programming in AJAX using PHP ";
?>


The AJAX 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.php','targetDiv')">
</form>
<div id="targetDiv">
<p>The retrieved message will appear here</p>
</div>
</body>
</html>


Before clicking the button : 

After clicking the button :

The button is connected to a Javascript function, getData and passes two arguments to that function - "data.php", 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.

Top