Few days ago, Mike emailed me and asked me how can i call a server script( php file) from jQuery in every second.Since, there was no built-in mechanism for this in jQuery, I came up with this solution of displaying time of server using Ajax, PHP and jQuery.You can use setinterval() method avaiable in javaScript to accomplish this task using jQuery.
View Live Demo
HTML Code:
<div align="center" id="timeval">--:--:--</div> <button id="stop">Stop</button>
There are mainly two elements one is “div” with id “timeval” which displays the the time and the other one is “button” with id “stop” to stop the calling the PHP file in the regular interval.
JavaScript Code:
<script src="jquery.js"></script> <script> $(document).ready(function() { //ajaxTime.php is called every second to get time from server var refreshId = setInterval(function() { $('#timeval').load('ajaxTime.php?randval='+ Math.random()); }, 1000); //stop the clock when this button is clicked $("#stop").click(function() { clearInterval(refreshId); }); }); </script>
As you can see above, setInterval() function is used to call the php file in every second, where 1000 means 1000 millisecond which equals to one second.And, the load() function of jQuery is used to call the Ajax. And, you might be wondering why I’ve passed “randval” to “ajaxTime.php”, you can read this post of mine about the problem of getting same value from ajax. And when the button with id “stop” is called the clearInterval() functions clears the interval ID generated by setInterval() and stop calling the PHP file at regular interval.
PHP code :
<?php
echo date("g:i:s A");
?>
As you can see the php code in the ajaxTime.php is fairly simple, it just displays the current server time.
You can download the demo by clicking here
Related posts:
