php / javascript - 使用ajax自动更新客户端

I am using PHP write the server side of the web page, and javascript to build the client side.

There is a div on the website that will show the data received from server side, for example, Let's say showing the current number of registered users in the databases. This number will keep changing in an unknown period of time. For example, the number could be the same in 10 hours, and it could increment by 1000 in 10 minutes.

My first question is, what is the best approach to do this functionality so that website can always show the latest or almost latest value of this data?

My original approach is using Javascript AJAX and wrapped by setInterval(1000) (-1 second) to send Ajax request to the server side. But I am not sure if this is too heavy for client side (because javascript is single threaded, it might be slow if there is a function running within each 1 second) or even server side( for example, if hundreds of users open this website and hundreds of requests will be sent to server side). So is this ok?

My second question is, if this is not a good approach, what else can I do to achieve the same goal. I was thinking about using the other way around. For example, if there is update in the server side, then use PHP in the server side to push this update to client side, or even directly change the data shown in the HTML using PHP scripting. Is this possible? if it is, is this a good approach?

Any codes or examples provided would be really appreciated.

You can certainly use AJAX for updates that are spread out over time, but if you want to connect to your server every second or so, I would advice against it.

You have a couple of options here:

  • As @Kay already mentioned, long polling might be an option.

  • Alternatively, you might want to look into WebSockets or a framework that supports WebSockets, like Meteor

You can use simple long polling.

The client side requests a script "/counter?oldvalue=...&timestamp=.... The server does not immediately return a value if it was not changed, but idles for up to 30 seconds.

If the counter value gets changed, then you return the updated value immediately.