jQuery Datatables is one of the best libraries I’ve used and supports just an incredible amount of features, however, I found it difficult to change the data source since it’s created dynamically from other elements on the page (dropdown, date fields), so I came up with destroying and re-creating the table.
First, we import the library and create the Table, with the header columns defined.
Email Name Office
Next, I have a few data filters on the page
Last 14 days
This Month
Last Month
This Year
Last Year
Custom
From To
Refresh
var oTable;
fnServerObjectToArray = function () {
return function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": 'datefrom=' + $('#DateFromUniqueUsers').val() + '&dateto=' + $('#DateToUniqueUsers').val() + '&DateRange=' + $('#DateRangeUniqueUsers').val(),
"success": function (json) {
var a = [];
for (var i = 0, iLen = json.aaData.length; i < iLen; i++) {
var inner = [];
inner.push(json.aaData[i].Email);
inner.push(json.aaData[i].Name);
inner.push(json.aaData[i].Office);
a.push(inner);
}
json.aaData = a;
fnCallback(json);
}
});
}
}
$(document).ready(function () {
RefreshTable();
});
function RefreshTable() {
if (oTable)
oTable.fnDestroy();
if (fnServerObjectToArray) {
oTable = $('.datatable').dataTable({
"bJQueryUI": true,
"bSortClasses": false,
"aaSorting": [[0, 'asc']],
"bAutoWidth": true,
"bInfo": true,
"sScrollY": "100%",
"sScrollX": "100%",
"bScrollCollapse": true,
"sPaginationType": "full_numbers",
"bRetrieve": true,
"bProcessing": true,
"sAjaxSource": $('.datatable').attr('data'),
"aoColumns": [
{ sType: 'string' },
{ sType: 'string' },
{ sType: 'string' }
],
"fnServerData": fnServerObjectToArray()
});
}
}
function SetDateRangesUniqueUsers() {
$('#ShowCustomUniqueUsers').toggle($('#DateRangeUniqueUsers').val() == 'Custom');
$('#GroupByDivUniqueUsers').toggle($('#DateRangeUniqueUsers').val() != 'AverageByWeekday');
}
Please note, this is only the way I choose to use the jQuery Datatables plugin, but you may use it as you need for your use cases.
Quick Links
Legal Stuff