2

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);
Vonder
  • 4,033
  • 15
  • 44
  • 61
  • By 'dynamic' did you mean the count should change automatically when the db changes on the server or just that it should display somewhere on the page and update every two seconds (when you make the ajax call)? – charsi Aug 14 '16 at 19:28

2 Answers2

3

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.

Community
  • 1
  • 1
charsi
  • 2,917
  • 22
  • 40
2

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.

Darren
  • 68,902
  • 24
  • 138
  • 144
  • This won't be ''dynamic". I think vonder wants the count to update on the client in realtime. – charsi Aug 14 '16 at 18:15
  • @charsi - this will update each time the AJAX request is made. The OP is using the $.ajax method already so this makes sense to build on top of what they have already got in place as a solution. – Darren Aug 14 '16 at 19:17
  • From his question it seems like he wants it to update automatically without any further ajax calls. I have asked him to clarify if thats the case. – charsi Aug 14 '16 at 19:19
  • 1
    @charsi - he has the AJAX request on a setTimeout so he is polling the server for any new updated rows. I believe the OP is struggling with displaying the contents from the request in the document object model, hence my answer. I've also pointed out that polling the server ever 2 seconds may not be the most efficient. – Darren Aug 14 '16 at 19:21
  • 1
    Yes you are right. I just saw that he is using a timeout to do the ajax call. – charsi Aug 14 '16 at 19:26