Peminator
Peminator

Reputation: 852

jQuery or other JS to get server time and sync ticking clock and set event launch on exact time

I need to fetch exact time from server to client side by jQuery, tha best approach maybe would be to read the GET headers where the date is formatted like this

HTTP/1.1 200 OK => 
Server => nginx
Date => Fri, 30 Sep 2011 09:10:23 GMT
...

anyone has idea how to read this to jQuery and show client the synced clock running ? ideally with option to add an event to be launched on defined time exactly ? please no server side php, just pure JS or jQuery

Upvotes: 2

Views: 2228

Answers (2)

James Allardice
James Allardice

Reputation: 165971

JavaScript cannot access the HTTP headers of the page it is running on, but it can however read the response headers of an XMLHttpRequest object. You can therefore make a GET request to anywhere really, and then access the headers of the response. With jQuery, it's nice and simple:

$.get(document.location, function(data, text, xhr) {
    var headers = xhr.getAllResponseHeaders();
});

From there, you will be able to parse the headers to get the date as required.

Upvotes: 3

Samich
Samich

Reputation: 30115

I think it's imposible because javascript are executing on the client side and it's no ability to read response headers in it. So, only server side coding can help you:

  1. You can put this time in hidden field and than show time to user base on fields value.
  2. Make AJAX call to some handler whitch will return time value. But it's still server side work.

Here is discussion about headers: Accessing the web page's HTTP Headers in JavaScript

Upvotes: 0

Related Questions