Differences

This shows you the differences between two versions of the page.

Link to this comparison view

computers:php_ajax_datetime [2015/03/24 05:42] (current)
Line 1: Line 1:
 +====== PHP Ajax datetime ======
 +Show date/time on the page and update it automatically dynamically using Ajax.
  
 +Download it {{computers:​ajax_datetime.zip}}
 +
 +
 +===== Example =====
 +<​html>​
 +<iframe frameborder=0 scrolling="​no"​ height="​50px"​ width="​80%"​ align="​middle"​ src="/​code/​examples/​ajax_datetime/"></​iframe>​
 +</​html>​
 +
 +===== Usage =====
 +Just put the following where you want the time to show up;
 +<code php>
 +//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)";​
 +</​code>​
 +
 +
 +===== Server Side Code  =====
 +
 +The file "​datetime.php"​ contains following code:
 +<code php>
 +/* --- 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>​
 +';
 +</​code>​
 +
 +The file "​time.php"​ contains following code:
 +<code php>
 +echo date('​l,​ Y/m/d h:i:s A', time()); ​ //time() is optional/​default behavior;
 +</​code>​
 +
 +
 +
 +====== Candidate Code Suggestions ======
 +Add your suggestions and links here.