As per the information provided on the Datatables website, the feature "retain row selection over a data reload" should work seamlessly. However, I am facing issues with it when using data from an ajax source.
Below is the code snippet showcasing how I am creating my table:
oTable = $('#fileList').DataTable({
select: true,
"ajax": {
"url": "./data.php",
"type": "GET"
},
rowId: 'Index',
"createdRow": function (row, data, dataIndex) {
$(row).addClass(data[2]); //set formatting from data[2]
}
});
Following the guide from the reference mentioned above, initially I tried refreshing the table every five seconds with the following code:
setInterval(function () {
oTable.ajax.reload();
}
However, the issue persisted where any selected row would get deselected every five seconds. To address this, I attempted a more explicit approach by saving the selected rows into an array and re-selecting them inside the setInterval function:
setInterval(function () {
var selectedRows = [];
// Store all selected rows in an array:
sel = oTable.rows('.selected').every(function (rowIdx) {
selectedRows.push(rowIdx);
});
oTable.ajax.reload();
console.log(selectedRows);
// Re-select all rows from the array
for (var i = 0; i < selectedRows.length; i++) {
console.log("selecting ",selectedRows[i]);
oTable.rows(selectedRows[i]).select();
}
}, 5000)
});
When checking the Console, I noticed that a selected row (in this case, the third row) was correctly captured in the array:
Array [ 2 ]
selecting 2
However, the rows were not getting re-selected. Manually selecting the row using oTable.rows(2).select();
in the console worked fine but not within the setInterval
block.
I suspect that the issue might be related to the rowID property. This is how I defined the table structure in the HTML:
<table id="fileList" class="display">
<thead>
<tr>
<th>Index</th>
<th>Status</th>
<th>Owner</th>
</tr>
</thead>
</table>
The data is fetched from a PHP script which returns an array like:
{"data":[["1", "foo", "bar"], ["2", "fuz", "baz"]}
where the first item represents the index.