Vonder
Vonder

Reputation: 4051

How to display dynamically updated data in JQuery

I am trying to display how many rows are there in the database. This should be dynamically updated, so when the number of rows change, the displayed number is also updated. I tried to print it with PHP but it is not dynamic.

Here is the index file:

  <script>
      $(document).ready(function() {
          setInterval("ajaxcall()",2000);
      });

      function ajaxcall() {
       $.ajax({
       type: "GET",
       url: "count.php"
       success: function(response){
           json_object = JSON.parse(response)
           var count = json_object.count

       // HOW TO DISPLAY COUNT SO IT IS DYNAMIC
       }
       });
       }
       </script>

And here is the count.php

$num_rows = mysql_num_rows($result);
echo json_encode($num_rows);

Upvotes: 2

Views: 1969

Answers (2)

charsi
charsi

Reputation: 3817

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.

Upvotes: 3

Darren
Darren

Reputation: 70718

You can update a DOM element with the count variable from the AJAX response.

Something like the following:

<span id="database-results">
</span>

Then in your AJAX success call, append the count variable to the HTML element:

success: function(response) {
          json_object = JSON.parse(response)
          var count = json_object.count

          $("#database-results").text(count);
}

As an additional note, you would be spamming the server with AJAX requests every 2 seconds, depending on your user base this may be something to consider.

Upvotes: 2

Related Questions