Is there a way to ‘listen’ for a database event and update a page in real time?

This isn’t too difficult. The simple way would be to add via .append:

$( '#table > tbody:last').append('<tr id="id"><td>stuff</td></tr>');

Adding elements real-time isn’t entirely possible. You’d have to run an Ajax query that updates in a loop to “catch” the change. So, not totally real-time, but very, very close to it. Your user really wouldn’t notice the difference, though your server’s load might.

But if you’re going to get more involved, I’d suggest looking at DataTables. It gives you quite a few new features, including sorting, paging, filtering, limiting, searching, and ajax loading. From there, you could either add an element via ajax and refresh the table view, or simply append on via its API. I’ve been using DataTables in my app for some time now and they’ve been consistently cited as the number 1 feature that makes the immense amount of data usable.

–Edit —

Because it isn’t obvious, to update the DataTable you call set your Datatables call to a variable:

var oTable = $('#selector').dataTable();

Then run this to do the update:

  oTable.fnDraw(false);

UPDATE — 5 years later, Feb 2016:
This is much more possible today than it was in 2011. New Javascript frameworks such as Backbone.js can connect directly to the database and trigger changes on UI elements including tables on change, update, or delete of data….it’s one of these framework’s primary benefits. Additionally, UI’s can be fed real-time updates via socket connections to a web service, which can also then be caught and acted upon. While the technique described here still works, there are far more “live” ways of doing things today.

Leave a Comment