Search code examples
phpjquerymysqlhtml-tablepolling

Can Jquery update/insert new table rows when new database entry?


I have a basic html table that's populated using PHP/mysql. Can anyone suggest how I can update or insert a new table row at the top of the table when a new row is inserted into my database using jQuery?

I have Googled but can only find how to update a div e.g.:

$(document).ready(function(){

var auto_refresh = setInterval(
function ()
{
$('#some_div').load('test.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds

});

I'd really appreciate it if someone can help me with this.


Solution

  • Javascript cannot receive push notifications from the database, so the example you've given is correct.

    You can, however, poll the server for changes by returning some value to Javascript via AJAX that tells you whether data has changed, then fire the AJAX request that refreshes the part of the page showing those results.

    Either way, you have to poll the server for changes with a setInterval() call. There are ways to enable HTTP streaming, but that's a bit above and beyond the level of this question.

    EDIT: For brevity, I'll write an example in jQuery:

    var getCurrentDate = function() {
      return (new Date()).toUTCString();
    };
    
    var lastPing = getCurrentDate();
    
    setInterval(function() {
      $.post(
        '/service/getNewData',
        { from: lastPing },
    
        function(data) {
          // set the timestamp for the next request
          lastPing = getCurrentDate();
    
          // assuming the server returns a JSON array of rows
          $('body').append('<p>Last inserted ID: ' + data[data.length - 1].ID + '</p>');
    
          // you could run a for loop here for each row in data
          for(var i = 0; i < data.length; i++) {
            // ....
          }
    
        }
      );
    }, 5000);
    

    This code requests the /service/getNewData URL and sends a UTC string of the last time the request was sent; this enables the service to find rows with timestamps larger than the UTC timestamp sent by the AJAX call. All you need is to send the rows back as a proper JSON string with the proper HTTP headers and you're all set.

    See json_encode().