Welcome to Code Couch

Using AJAX to update the time on a web page from the server

Posted by at 12:25pm on October 12, 2008.

Sometimes the easiest way to begin to understand something is through an example. In an attempt to better explain how you can use AJAX to fetch some data from the server and then display it on a web page (without refreshing the page), I constructed the following example PHP page:

<?
if (isset($_GET['xhttp'])) {
	$counter = date("d M Y h:m:s");
	echo $counter;
} else {
?>
<html>
<head>
<title>Test some XHTTP</title>
<script type="text/javascript">
function getHTTPObject() {
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp = false;
			}
		}
	@else
		xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	return xmlhttp;
};
 
function fetchData() {
	http = getHTTPObject();
	http.open('get', "<?= $_SERVER['SCRIPT_NAME']; ?>?xhttp=true", true);
	http.onreadystatechange = function() {
		if (http != null && http.readyState == 4) {
			document.getElementById('displayCounter').innerHTML = http.responseText;
		}
	};
	http.send(null);
};
 
function initPage() {
	http = null;
	pageTimerHandle = setInterval('fetchData()', 2000);
};
 
window.onload = initPage;
</script>
</head>
<body>
	<h1>Test page</h1>
	<p>This page is using AJAX to update the current time every two seconds.</p>
	<div id="displayCounter"><?= date("d M Y h:m:s"); ?></div>
</body>
</html>
<? } ?>

This block of code is PHP and basically tests to see whether a (GET) parameter (called xhttp) was passed in to the URL:

<?
if (isset($_GET['xhttp'])) {
	$counter = date("d M Y h:m:s");
	echo $counter;
} else {
?>

If the xhttp GET parameter was present in the URL, then the server time is sent back, otherwise the whole HTML page is delivered. This allows us to deliver two very different “pages” of data back to the browser using the same single PHP file.

The following block of code is used to output the full name of the PHP page being run (the file name) and merely removes the need to specify the file name in the code itself:

<?= $_SERVER['SCRIPT_NAME']; ?>

The final block of PHP that is prominent in the page is:

<?= date("d M Y h:m:s"); ?>

This writes out the current date and time to the page (and mimics the same date and time format that will be returned if the PHP file is requested with the GET parameter of xhttp added to it).

Everything else is just HTML and Javascript.

Post to Twitter

Tags: , ,

Comments

There are no responses to this post.

Leave a reply

Comments are closed for this post.