• I have a website that contains a single toggle switch with 2 states.
  • There are currently 2 (or more) clients viewing the site.


  • 1 client flicks the toggle switch.

How can I reflect that change across everyone currently visiting the site?

The simplest way I thought of was to save the current state of the switch server side, and have the clients constantly send AJAX requests asking for the state of the switch, which it updates.

The problem with this approach is, especially when there are many clients, the server will be constantly spammed by requests; even if no change has happened.

The other approach I thought of was to notify the server when 1 client makes a change, and somehow broadcast that change to all the currently connected clients.

Unfortunately though, HTTP being stateless, I would have to maintain a list of currently connected clients server side. I don't know how I would detect when a client is no longer viewing the page though, or how I could send a message to a client without them first sending a request.

What is the simplest way to achieve this that doesn't rely on clients constantly polling the server?

In case it's not obvious, this is a greatly simplified example. My real project is a game where there will be many "switches", each of which may contain many different possible states.


You asked to keep it simple:

Like you, I would keep the "official" state of the switch server side.

I'd then bundle that state into the reply to any other calls the client might make.

For example, make the reply object returned by the server look something like

class DataFromServer() {
    bool mySwitchState;
    int errorCode;
    string errorMessage;
    object ActualData;

No matter what request your client makes of you, respond with one of these, properly populated.

This way you don't need to keep track of your clients and you won't push to clients who no longer care.

If you truly need a push mechanism (a game might), you may want to look into Socket.io (per a comment from @AndrewJenkins) or some other push technology such as long polling.

  • Thanks. Really the only communication is the periodic updates, besides the odd submission of data, so just including the updates in a packet already being sent wouldn't help. I also looked into Socket.io, but since I'm using PHP, it required a lot of other things for it to work (since I'd have to use elephant.io). Since this is just a toy project (a chat client), I opted to just include a refresh button since polling ended up using a lot of data in my tests. Thanks anyways for your answer though. Mar 1 '16 at 22:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.