Auto-refreshing dynamic content using AJAX and PHP
The following script will use PHP and Ajax (XMLHTTPRequest) to retrieve current server time in every 10 seconds and then insert the date/time into the html page.
1, html file: time.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>Auto-refreshing dynamic content using AJAX and PHP</title>
<script type=”text/javascript” src=”time.js“></script>
</head><body onload=”ajax(page,’scriptoutput‘)”>
<p>Current Server date & time (updated every 10 seconds):<br />
<span id=”scriptoutput“></span></p>
</body>
</html>
2, Ajax file: time.js
var page =“/time.php?time=”+date.getTime();
function ajax(url,target)
{
// native XMLHttpRequest object
document.getElementById(target).innerHTML = ’sending…’;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = function() {ajaxDone(target);};
req.open(”GET”, url, true);
req.send(null);
// IE/Windows ActiveX version
} else if (window.ActiveXObject) {
req = new ActiveXObject(”Microsoft.XMLHTTP”);
if (req) {
req.onreadystatechange = function() {ajaxDone(target);};
req.open(”GET”, url, true);
req.send();
}
}
setTimeout(”ajax(page,’scriptoutput‘)”, 10000); //10 seconds
}
function ajaxDone(target) {
// only if req is “loaded”
if (req.readyState == 4) {
// only if “OK”
if (req.status == 200 || req.status == 304) {
results = req.responseText;
document.getElementById(target).innerHTML = results;
} else {
document.getElementById(target).innerHTML=”ajax error:\n” +
req.statusText;
}
}
}
3, PHP file: time.php
<?php
putenv(’TZ=America/New_York’);
echo date(”Y-m-d h:i:s A”, time());
?>
4, Save and upload these files to your server, open time.html and you will see the html page refreshes it’s time every 10 seconds.
Ref: http://www.openhosting.co.uk/articles/webdev/6004/
Popularity: 3%

(3 votes, average: 4.33 out of 5)

















































Yemek Tarifleri said,
March 23, 2008 @ 5:00 pm
Thank you
Best Posting