-1

I want to have a page that uses a mySQL database for its information, let's just say its a 0 or 1

I want the page to auto refresh a div with the value 0 or 1 from the database at a specific interval.

But I would like anyone who is viewing the page to get the same information at the same time. So I would like the server to be in charge of the interval.

How could I do this?

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Jason Portnoy
  • 757
  • 8
  • 23
  • 2
    websockets or setInterval(recursive setTimeout) with ajax.. – vp_arth Apr 04 '14 at 20:59
  • Thinking abstractly, I'd have a single page that queries the database when called, and returns the 0/1 from the database, and possibly defines a 'call me in X seconds' value. Then, when the main web page loads, make a `GET` request to that page, refresh the div with the 0/1 value, and set a javascript interval based on either the 'call me in X seconds' value, or just have it run every few seconds, whichever is more beneficial. – beercodebeer Apr 04 '14 at 20:59
  • 1
    Send a GET to the server. Server sends a response with the timestamp that the client should make the next request. Don't forget to factor in latency offsets and differences in the client time/server time. You can do this by sending the client time to the server so that it can apply it as an offset. Or, you could use something like socket.io/WebSockets to setup a publish/subscribe system. – crush Apr 04 '14 at 20:59
  • Why would someone downvote this months later without leaving a comment as to why? – Jason Portnoy Sep 23 '15 at 20:23

2 Answers2

2

There are several possibilities:

1) Websockets is the latest of the technologies. If you really want near realtime update of the page and have an Infrastructure providing the possibilities, that is the way to go

2) Comet or long polling would be a second alternative

3) The most primitive - but working - startingpoint would be to constantly poll your server. Stackoverflow Article

Community
  • 1
  • 1
Thomas Junk
  • 5,588
  • 2
  • 30
  • 43
-2

You can use a JavaScript timer that will check server for any updates and return updated values to the client using Ajax. You can use setTimeout() function as given here:Jquery/Ajax call with timer

A sample you can try (function worker() { $.get('ajax/test.html', function(data) { // Now that we've completed the request schedule the next one. $('.result').html(data); setTimeout(worker, 5000); }); })();

Community
  • 1
  • 1
Aishwarya Shiva
  • 3,460
  • 15
  • 58
  • 107