You need to either -
- Periodically make ajax calls to check for updated value.(This is what you are currently doing.) -- Usually a bad idea if users are going to be connected for very long.
- Or, a better solution would be to use HTML5 web sockets instead.
Projects like socket.io make it very easy to implement websockets on a javascript server(node). But PHP also has a few options. -
- Ratchet - Similar to socket.io but built for PHP.
- Elephant.io - Also a PHP implementation of websockets but it is a ws 'client' which is meant to work on the server. So, you'll probably have to deploy node and socket.io on the server as well and drive it using elephant.io to handle websocket communication with the other clients.
- phpsocket.io - "A server side alternative implementation of socket.io in PHP based on Workerman." - according to its github page.
There isn't much documentation on phpsocket.io but the API looks simple enough from the examples in their readme. Something like this should work for you --
<?
use PHPSocketIO\SocketIO;
// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
$socket->on('get count', function($msg)use($io){
$num_rows = mysql_num_rows($result);
$io->emit($num_rows, $msg);
});
});
and on the client--
var count = 0;
// check if browser supports websockets
if ("WebSocket" in window) {
var ws = new WebSocket("ws://yourdomain.com:2021/");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("get count");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
json_object = JSON.parse(response)
count = json_object.count
$("#database-results").text(count);
};
}
*Disclaimer -- I haven't tested the code above or used the phpsocket.io library before. So the code might not work. Also, Ratchet looks to be a more mature project so you should investigate it further if you want a more robust solution for your app.
I got a lot of the above info from this so thread. Some info there is however a few years out of date and the top rated answers there don't offer the best solutions for today.