PHP Ajax datetime

Show date/time on the page and update it automatically dynamically using Ajax.

Download it ajax_datetime.zip

<iframe frameborder=0 scrolling="no" height="50px" width="80%" align="middle" src="/code/examples/ajax_datetime/"></iframe>

Just put the following where you want the time to show up;

//Just include the datetime file;
include ('datetime.php');
 
//Optionally show how quickly it will refresh;
echo "<br/>Current Server date & time (updated every $refreshSeconds seconds)";

The file “datetime.php” contains following code:

/* --- CONFIG BEGIN --- */
$path2datetimefile = 'time.php'; //path to the file that ONLY outputs date/time;
$refreshSeconds	= 1; //seconds before time update;
/* --- CONFIG END, DO NOT EDIT BELOW THIS POINT --- */
 
putenv('TZ=America/Los_Angeles');
echo '<strong id="ajax_datetime">Sending ... </strong>';
 
// Output the javascript needed for Ajax;
echo '
<script type="text/javascript">
function getAjaxDatetime() {
	var $ajax;	//ajax object;
	try { 	// Firefox, Opera 8.0+, Safari;
		$ajax = new XMLHttpRequest(); 	
	}
	catch (e) { // Internet Explorer
		try { $ajax = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch (e) {
			try { $ajax = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch (e) { alert("Your browser does not support AJAX!");
			return false;
			}
		}
	}
 
	$ajax.onreadystatechange = function() {
		if($ajax.readyState==4) {
			//document.myForm.time.value=$ajax.responseText;
			document.getElementById(\'ajax_datetime\').innerHTML = $ajax.responseText;
		}
	}
	$ajax.open("GET", "',$path2datetimefile,'", true);
	$ajax.send(null);
	setTimeout("getAjaxDatetime(\'ajax_datetime\')",',$refreshSeconds*1000,');	
}
getAjaxDatetime();
</script>
';

The file “time.php” contains following code:

echo date('l, Y/m/d h:i:s A', time());  //time() is optional/default behavior;

Candidate Code Suggestions

Add your suggestions and links here.