<pedrocorreia.net ⁄>
corner
<mySearch ⁄> <mySearch ⁄>

corner
 
corner
<mySnippets order="rand" ⁄> <mySnippets order="rand" ⁄>

corner
 
corner
<myContacts ⁄> <myContacts ⁄>

<email ⁄>


pc@pedrocorreia.net

<windows live messenger ⁄>


pedrojacorreia@hotmail.com

<myCurriculum type="pdf" ⁄>


Download
corner
 
corner
<myBlog show="last" ⁄> <myBlog show="last" ⁄>

corner
 
corner
<myNews show="rand" ⁄> <myNews show="rand" ⁄>

corner
 
corner
<myNews type="cat" ⁄> <myNews type="cat" ⁄>

corner
 
corner
<myQuote order="random" ⁄> <myQuote order="random" ⁄>

corner
 
corner
<myPhoto order="random" ⁄> <myPhoto order="random" ⁄>

<pedrocorreia.net ⁄>
corner
 
corner
<myAdSense ⁄> <myAdSense ⁄>

corner
 
corner
<myVisitorsMap ⁄> <myVisitorsMap ⁄>

corner
 
 

<Ajax Server Date/ Time ⁄ >




clicks: 14772 14772 2008-07-27 2008-07-27 goto mySnippets mySnippets javascript  Download  Bookmark This Bookmark This



The main goal of this script's very simple, show server date/ time.

Let's suppose you run a website on which you have some signup form or a poll or something else that have a specific deadline, this is at a precise time that some specific functionality will not be available; for instance a poll that ends at 23:59 or a signup form that only starts at 10am.


Of course, you can simply check/ make that validation at server-side, however it'd be nice (or at least I think it would help) that your user knows exactly what's your server time. Since you can't trust on "client's clock", only your server time clock's really trustfully.
i.e., let's just inform our user that whatever its computer clock's showing, it doesn't matter "so please regular yourself for this server clock".


Events.js, this file's responsible for events management, that is, our page has elements and those elements will react to events/ triggers, with this class we'll be able to add or remove events, such as onchange, onload, etc, etc.
  1. /**
  2. * Static Class Events
  3. * Manage Events
  4. */
  5. Events = function(){}
  6.  
  7. /**
  8. * Add Event
  9. *
  10. * Full credits to (I just made a few mods):
  11. * http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
  12. *
  13. * @param Object
  14. * @param Object
  15. * @param Object
  16. */
  17. Events.AddEvent = function(obj, type, fn){
  18. if(!obj) return;
  19.  
  20. this.RemoveEvent(obj, type, fn);
  21. if (obj.addEventListener) {
  22. obj.addEventListener(type, fn, false);
  23. }
  24. else {
  25. if (obj.attachEvent) {
  26. obj["e" + type + fn] = fn;
  27. obj[type + fn] = function(){
  28. obj["e" + type + fn](window.event);
  29. }
  30. obj.attachEvent("on" + type, obj[type + fn]);
  31. }
  32. }
  33. }
  34.  
  35. /**
  36. * Remove Event
  37. *
  38. * Full credits to (I just made a few mods):
  39. * http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
  40. *
  41. * @param Object
  42. * @param Object
  43. * @param Object
  44. */
  45. Events.RemoveEvent = function(obj, type, fn){
  46. if (obj.removeEventListener) {
  47. try{obj.removeEventListener(type, fn, false);} catch(e){}
  48. }
  49. else{
  50. if (obj.detachEvent) {
  51. obj.detachEvent("on" + type, fn);
  52. obj[type + fn] = null;
  53. obj["e" + type + fn] = null;
  54. }
  55. }
  56. }




Misc.js, Static class, has some common tasks, such as create a HttpRequest
  1. /**
  2. * Static Class Misc, contains some
  3. * miscellaneous methods/ settings
  4. *
  5. * @author pedrocorreia.net
  6. */
  7. Misc = function(){}
  8.  
  9. /**
  10. * Hack IE to avoid HTTP Get cache problems
  11. *
  12. * @param String Url
  13. */
  14. Misc.AntiCacheRand = function(aurl){
  15. var rnd = encodeURI(Math.random());
  16. aurl += (aurl.indexOf("?") >= 0) ? "&foo=" + rnd : "?foo=" + rnd;
  17.  
  18. return aurl;
  19. };
  20.  
  21. /**
  22. * Create HttpRequest.
  23. * This request allow us to communicate with the server
  24. *
  25. * @return HttpRequest
  26. */
  27. Misc.CreateHttpRequest = function(){
  28. if (window.XMLHttpRequest) { // Mozilla, Safari,...
  29. http_request = new XMLHttpRequest();
  30.  
  31. if (http_request.overrideMimeType) {
  32. http_request.overrideMimeType('text/html');
  33. }
  34. }
  35. else
  36. if (window.ActiveXObject) { // IE
  37. try {
  38. http_request = new ActiveXObject("Msxml2.XMLHTTP");
  39. }
  40. catch (e) {
  41. try {
  42. http_request = new ActiveXObject("Microsoft.XMLHTTP");
  43. }
  44. catch (e) {
  45. }
  46. }
  47. }
  48.  
  49. if (!http_request) {
  50. alert('Giving up :( Cannot create an XMLHTTP instance');
  51. return false;
  52. }
  53.  
  54. return http_request;
  55. };
  56.  
  57. /**
  58. * Get HtmlControl reference
  59. *
  60. * note: this is a static method, Misc Class
  61. * doesn't have to be instantiated
  62. *
  63. * @param String
  64. * @return Element object
  65. */
  66. $ = function(element){
  67. if (document.getElementById){
  68. return document.getElementById(element);
  69. }
  70. };




ajax.php will answer our request
  1. <?php
  2. /**
  3. * Get the request and answer it
  4. */
  5.  
  6. include_once("_Class_/class.MyServerTime.php");
  7.  
  8. $my_server_time=new MyServerTime($_GET["time_format"]);
  9. echo $my_server_time->Date();
  10. ?>




class.MyServerTime.php, this class will return our server current time regarding a specific format. You can specify this format in your ajax call, but we'll see this ahead
  1. <?php
  2.  
  3. /**
  4. * Get Date/ Time
  5. *
  6. * @author pedrocorreia.net
  7. */
  8. class MyServerTime{
  9. private $_format; //time format
  10.  
  11. /**
  12. * Constructor method
  13. *
  14. * @param String $format
  15. */
  16. public function __construct($format){$this->Format($format);}
  17.  
  18. /**
  19. * Getter/ Setter TimeFormat
  20. *
  21. * @param String $value
  22. * @return String
  23. */
  24. public function Format($value=""){
  25. if($value){$this->_format=$value;}
  26. else{return $this->_format;}
  27. }
  28.  
  29. /**
  30. * Get Date
  31. *
  32. * @return DateTime
  33. */
  34. function Date(){return gmdate($this->Format());}
  35.  
  36. }
  37. ?>








AjaxServerTime.js, our main javascript class. It'll be responsible to communicate with the server and show the answer to the user. It has some basic functionalities such as show the time, enable and stop the timer, etc;
  1. /**
  2. * Class AjaxServerTime
  3. *
  4. * This class's responsible for server communications
  5. *
  6. * @author pedrocorreia.net
  7. */
  8.  
  9. /**
  10. * AjaxServerTime Constructor
  11. *
  12. * @param Object Settings
  13. */
  14. AjaxServerTime = function(settings){
  15. this._settings=settings;
  16. this.interval=-1;
  17. }
  18.  
  19. /**
  20. * Get server time and show it to the user
  21. */
  22. AjaxServerTime.prototype.Show = function(){
  23. var qryStr=this._settings.server_file+"?time_format="+this._settings.format;
  24. var url_request = Misc.AntiCacheRand(qryStr);
  25. var http_request = Misc.CreateHttpRequest();
  26.  
  27. var id=this._settings.id; //html object id
  28.  
  29. http_request.onreadystatechange = function(){
  30. var state = http_request.readyState;
  31. //request complete and successfully
  32. if (state == 4 && http_request.status == 200) {
  33. $(id).innerHTML=http_request.responseText;
  34. }
  35. }
  36.  
  37. http_request.open("GET", url_request, true);
  38. http_request.send(null);
  39. }
  40.  
  41. /**
  42. * Create a Timer
  43. * Will execute a specific funcion at every
  44. * specified seconds interval
  45. */
  46. AjaxServerTime.prototype.Timer = function(){
  47. var inst=this;
  48. var seconds=inst._settings.interval*1000;
  49. this.interval=setInterval(function(){inst.Show()},seconds);
  50. };
  51.  
  52. /**
  53. * Stop Clock
  54. */
  55. AjaxServerTime.prototype.StopTimer = function(){
  56. clearInterval(this.interval);
  57. this.interval=-1;
  58. }
  59.  
  60. /**
  61. * This method will just simply switch images
  62. * so that the user can know if it will
  63. * stop or start the clock
  64. *
  65. */
  66. AjaxServerTime.prototype.SwitchClock = function(){
  67. var img_filename;
  68. var img_alt;
  69.  
  70. var defs={
  71. "img_id": "clock_img", //html object id
  72.  
  73. "img_start": "start.png",
  74. "img_start_alt": "Restart Clock",
  75.  
  76. "img_stop": "stop.png",
  77. "img_stop_alt": "Stop Clock",
  78.  
  79. "img_folder": "_images_/"
  80. }
  81.  
  82. if(this.interval<0){
  83. img_filename=defs.img_stop;
  84. img_alt=defs.img_stop_alt;
  85. this.Timer();
  86. }
  87. else{
  88. img_filename=defs.img_start;
  89. img_alt=defs.img_start_alt;
  90. this.StopTimer();
  91. }
  92.  
  93. //update image attributes
  94. var img=$(defs.img_id);
  95. img.src=defs.img_folder+img_filename;
  96. img.alt=img.title=img_alt;
  97. }




Init.js, this is where initially events will be triggered. In this example we'll immediately show our server time in page loading; after that we'll call our Timer function, this will allow us to show our updated server time at every Y second(s) (in this example Y=1, however this time can easily configurable) the user will see our server time will constantly updated. I also made a simple example to stop and start the clock.
  1. /**
  2. * Startup function
  3. *
  4. * @author pedrocorreia.net
  5. */
  6. Init = function (){
  7.  
  8. var settings = {
  9. "id": "mySpanTime", //where will be written
  10. "interval": 1, //update frequency
  11. "format": "H:i:s", //DateTime format
  12. "server_file": "ajax.php" //file that will process our requests
  13. }
  14.  
  15. //create AjaxServerTime object
  16. var jx_server_time=new AjaxServerTime(settings);
  17.  
  18. //show server time, this is just a one time operation
  19. jx_server_time.Show();
  20.  
  21. //create a timer that will show our server time,
  22. //just like a normal clock
  23. jx_server_time.Timer();
  24.  
  25. //we'll add an event do stop and restart the clock by
  26. //just clicking in a image
  27. Events.AddEvent($("clock_img"),"click",function(){jx_server_time.SwitchClock();});
  28. }
  29.  
  30. Events.AddEvent(window, "load", Init);



Just a note to this code:
var settings = {
  "id": "mySpanTime", //where will be written
  "interval": 1, //update frequency
  "format": "H:i:s", //DateTime format
  "server_file": "ajax.php" //file that will process our requests
}


It's our object options, for example you can specify here: timer interval; date/ time format; etc.



our example page:
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  2. "DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  4. <head>
  5. <title>MyServerTime</title>
  6. <script type="text/javascript" src="_js_/Events.js"></script>
  7. <script type="text/javascript" src="_js_/Misc.js"></script>
  8. <script type="text/javascript" src="_js_/AjaxServerTime.js"></script>
  9. <script type="text/javascript" src="_js_/Init.js"></script>
  10. </head>
  11. <body>
  12. Current Server Time: <span id="mySpanTime"></span>
  13. <img src="_images_/stop.png" width="16" height="16" alt="Stop Clock" title="Stop Clock" id="clock_img" />
  14. </body>
  15. </html>





Here's a example of this snippet working:












If you have any doubt or found any error, please drop me an email.









clicks: 14772 14772 2008-07-27 2008-07-27 goto mySnippets mySnippets javascript  Download  Bookmark This Bookmark This