Although DataTables is built from the principle of progressive enhancement, it is often useful to be able to construct a table from an AJAX source. This can be done in one of two ways - either using the aData initialisation parameter which takes an array of data, or using the sAjaxSource initialisation parameter which will have DataTables go to that source with an XHR call and load data from there. This example shows the latter method in action. DataTables expects an object with an array called "aaData" with the data source.
| Rendering engine | Browser | Platform(s) | Engine version | CSS grade |
|---|---|---|---|---|
| Rendering engine | Browser | Platform(s) | Engine version | CSS grade |
$(document).ready(function() {
// create rdbhost sql engine object
var rdb = new SQLEngine("r0000000002","-",'rdbhost');
// getData is a callback for dataTables to fetch additional
// data dynamically as user pages up/down
var q = 'SELECT count(*) FROM css_data; '+
'SELECT * FROM css_data OFFSET ~~os~~ LIMIT ~~li~~';
function getData(sSource, aoData, fnCallback) {
// callback (with a callback) to format server data
// to suit dataTables, and calls the dataTables callback
// fnCallback with the reformed data
function cBack(json) {
var rows = json.result_sets[1].records.rows
var ct = json.result_sets[0].records.rows[0][0]
var newJson = {'aaData' : rows,
'iTotalDisplayRecords' : ct };
fnCallback(newJson);
}
// extract row boundaries from input aoData
var iDisplayStart, iDisplayLength;
for (var i=0; i<aoData.length; i++) {
if (aoData[i].name === 'iDisplayStart') {
iDisplayStart = aoData[i].value;
}
else if (aoData[i].name === 'iDisplayLength') {
iDisplayLength = aoData[i].value;
}
}
// embed row limits in query
var q0 = q.replace('~~os~~',iDisplayStart) {
.replace('~~li~~',iDisplayLength);
}
// query server, and pass data to cBack
rdb.query({ 'callback': cBack,
'errback': alert,
'q': q0 })
}
// put empty table into page
$('#dynamic').html( '<table cellpadding="0" cellspacing="0" border="0" '+
'class="display" id="example"><\/table>' );
// createTable callback invoked with 1-record dataset, to
// setup dataTables
function createTable(json) {
// create aoColumns data structure from header for datatable
var hdrs = json.records.header;
var aoCol = [];
for (var i=0; i<hdrs.length; i+=1) {
aoCol.push({'sTitle' : hdrs[i][1]});
}
// call dataTable with the aoColumns structure and other s
// 'sAjaxSource' is not used, but dataTable seems to expect it
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "/place/holder",
"aoColumns": aoCol,
"fnServerData": getData
} );
}
// get one record and table header from table
// pass rec and hdr to createTable callback
var qstart = 'SELECT * FROM css_data LIMIT 1';
rdb.query({ 'callback': createTable,
'errback': alert,
'q': qstart })
} );
Please refer to the DataTables documentation for full information about its API properties and methods.