Stayin' live polling datatables

We've got Saturday night fever here at QuayTech!  One of our clients requires a live sales dashboard that would essentially be 'staying live' ensuring it is constantly refreshing to show real-time data.  Live polling is the ability for a page to maintain/update itself without the need for user interaction.  The dashboard is utilising the DataTables widget (https://datatables.net/) to group the sales data, in different ways, tailored to the currently loggedin user.  How could we achieve live polling datatables to refresh the data currently being displayed on our dashboard?

THE How?

First things first your Datatable needs to be populated through a json web service call to return the data, as opposed to a model being passed to the view (if using C#).  In the code below you will see a URL is called, this endpoint needs to return the json object to the Datatable.  The data NEEDS to be returned in this format "{\"data\": " + jsonData + "}"; this allows the Datatable to see that the data being passed back is data for the Datatable.Note: The "bDestroy" : true variable that is being set here, this tells the Datatable that it is allowed to be destroyed and remade as necessary.

           var table = $(gridName).DataTable({lengthChange: false, paging: false, //pageLength: 5,"dom": '<"toolbar">frtip',"serverSide": false,"searching": true,"ordering": true,"lengthChange": true,"paging": true,"pageLength": 10,"bDestroy" : true,"ajax": {"url": "www.test.com/GetOrders"},"columnDefs": [{ "mDataProp": "CustomerAccountNumber", "targets": [0] },{ "mDataProp": "CompanyName", "targets": [1] },{ "mDataProp": "CustomerOrderReference", "targets": [2] },{ "mDataProp": "ReceivedOn", "targets": [3] }],
public async Task<string> GetOrders(){try{var orders =  GetOrdersByType("SOLD");string jsonData;if (orders.Count != 0){jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(orders);jsonData = "{\"data\": " + jsonData + "}";}else{jsonData = "{\"data\": \"\"}";}return jsonData;}catch (Exception){return "ERROR";}}

As long as we can identify the Datatable through an id, we are then able to call a reload on the ajax which will update the rows. The setInterval method is where the magic really happens, this sends a call to the method every 20 seconds in order for the datatables to poll.As a little bit of an extra, a count of the rows on the table is taken before the call and after, it is then noted if there is a difference and if so a notification is displayed to the user that a new order has been received as seen in the code below. I have added a two second delay on this check to allow the table to sort itself out before checking, else it is too fast to see any row changes.Note: datatableIDs is a string array of the IDs of the datatables that you are polling. Timing in JavaScript is in milliseconds so 20000 in the setInterval is actually 20 seconds.

function startDatatablePoller(datatableIDs){var lengthOfIds = datatableIDs.length;setInterval(function () {for (var i = 0; i < lengthOfIds; i++){pollDataTable(datatableIDs[i]);}}, 20000);}//Method to poll a datatable, by passing in the ID of a gridnamefunction pollDataTable(gridName) {var table = $(gridName).DataTable();var rowCountBefore = table.data().count()table.ajax.reload();setTimeout(function () {var rowCountAfter = table.data().count()//If a difference is found an alert for the datatable is displayed to the user//alerts are Id'd by datatable ID + -alert on the endif (rowCountBefore != rowCountAfter) {$(gridName + "-alert").fadeIn();}}, 2000)}

So there you have it, how to live poll a datatable.

Previous
Previous

10 command(line)ments of being a good developer

Next
Next

Secure File Transfer Party - FTP vs SFTP?