Ajax Example

In this section we will create a simple Ajax example for displaying the current date and time. This ajax example will help you to understand how ajax works.Date and time information are retrieved asynchronously from the server side php script. Our HTML page calls serverside php script to retrieve the today’s date. Once the time data is retrieved from the server, it uses javascript and css to display the time on the HTML page.

Here is the code of HTML File for the example :

<html>
<head>
<title>Ajax Example</title>
<script >
function postRequest(strURL) {
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
updatepage(xmlHttp.responseText);
}
}
xmlHttp.send(strURL);
}
function updatepage(str){
document.getElementById("result").innerHTML =
"<font color='red' size='5'>" + str + "</font>";;
}
function showCurrentTime(){
var rnd = Math.random();
var url="time.php?id="+rnd;
postRequest(url);
}
</script>
</head>
<body>
<h1 align="center"><font color="#000080">Ajax Example</font></h1>
<p><font color="#000080">&nbsp;This very simple Ajax Example retrieves the current date and time from server and shows on the form. To view the current date and time click on the following button.</font></p>
 <form >
 <p align="center"><font color="#000080">&nbsp;<input value="   Show Time   " onclick='JavaScript:showCurrentTime()' ></font></p>
 <div align="center"></div>
 </form>
 <div ></div>
 </body>
 </html>

When use clicks on the “Show Time” button, the showCurrentTime() is called. The the function showCurrentTime() calls the time.php using Ajax and then updates the time values retrieved from server.

Here is the code of PHP (time.php) file:

<?
print date("l M dS, Y, H:i:s");
?>

The above PHP code prints current date and time.

Hope this  ajax example has helped you in understanding the working of Ajax.