jCountdown

Server Time AJAX Demo

This demo shows you how to get the countdown timer to match the server time by passing the difference of server time to the plugin.

Setup

Setup is as simple as doing the following:

//HTML

<p id="timer"></p>

Create php file to return time server time:

<?php

// get_servertime.php

date_default_timezone_set('Europe/London');

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Fri, 1 Jan 2010 00:00:00 GMT"); // Date in the past
$now = time() * 1000;

$end = strtotime( $_GET['date'] ) * 1000;

# We only need the difference in dates
echo $end - $now;
?>

// JavaScript

var dateTo = "January 25, 2016 12:00:00",
	get_server_time = function() {
	    var time = null;
		$.ajax({
			url: 'get_serverdate.php',
			data : {
				date: dateTo
			},
			async: false,
			dataType: 'json',
			success: function( date, status, xhr ) {
				time = date;
			},
			error: function(xhr, status, err) {
				time = new Date();
				time = time.getTime();
			}
		});
		return time;
	},
	time = get_server_time();

$("#time").countdown({
	date: dateTo,
	serverDiff: time,
	yearsAndMonths: true
});