Server Clock showing date and time using AjaxWe have seen how to display current date and time of server in a page. But this gives us the server time when the page is rendered. It does not change or update as long as we are not refreshing the page to get the fresh data from server.
Using AjaxTo display changing clock showing server time is possible by using Ajax where we can display a clock by sending request to server and getting the data without refreshing the page.
There are two files for this demo ( download link at end of this page ) one is the file sending request and receiving data with Ajax.
We will fist develop a script where by clicking a button we can send a request to server to get the data. In the body of this file we have a button.
To this script we will add a timer to recursively call the same Ajax function in every second. This will get data from every second so we can display a changing clock showing server time.
Timer function: timer_function()On click of this button we trigger a function which uses a timer setTimeout. Inside this timer function we can change the refresh rate which is in milliseconds. Within this function we call our main Ajax function AjaxFunction().
At the end of AjaxFunction() we will call again our timer_function() to make it recursive.
In the main AjaxFunction() we send request to ajax-server-clock-demock.php file and get the server time. This data is displayed using a div layer.
The second file is the simple PHP file with one line of code giving current date and time of server. ajax-server-clock-demock.php
You can change the display format of the clock by changing the above code.
Ajax & PHP scripts Creating XMLHttp object in different browsers Sample Code: Get Method of Ajax form submission Server Clock:: Display real-time date and time of server Dependant drop down list box using Ajax & PHP Email validation using Ajax in a form Getting customer details by entering customer id using Ajax Progress Bar using Ajax Progress Bar using MySQL PHP & Ajax Displaying Message at client side using Ajax & PHP Web page HTML form validation using Ajax and PHP Form validation with onBlur event using Ajax and PHP
Json support in PHP json_encode to generate Json string from PHP Array data Json Data formatting to return database records to main script Searching MySql database as we type using Ajax Displaying all records based on selection of a drop down list box