'Dynamically adding rows to DataTables
I'm trying to add dynamic a row on https://DataTables.net .
I understand when I set processing: true , serverSide: true and ajax, I can't add new row in the table.
my code Datatable is:
var table = $('#example').DataTable({
dom: 'Bftip',
keys: true,
processing: true,
serverSide: true,
pageLength: 5,
columns: subColumns,
ajax: {
url: ...,
type: get,
},
buttons: [
{
text: '<i class="fa fa-plus" aria-hidden="true"></i>',
action: function () {
table.row.add({
"id": "",
"title": "t100",
"order": "100",
"mimeType": "101",
"thumpnailMimeType": "102",
"height": "103",
"width": "104"
});
//table.columns.adjust();
//table.draw();
},
},
]
});
I used table.columns.adjust(); and table.draw();, But they don't work.
I see how to add rows to DataTable too. but I think that's working for offline tables. I can see added the row with table.data(), but I can't see that in the table.
Thanks
Solution 1:[1]
Before you edited your question... You were using subTable.row.add instead of table.row.add.
Otherwise your code looks correct (Can't see what your actual columns are called because you are using a variable in the columns property) and this should work.
Here is a working Fiddle example. You can use this:
var table;
table = $('#example').DataTable({
dom: 'Bftip',
keys: true,
//processing: true,
//serverSide: true,
pageLength: 5,
columns: subColumns,
ajax: {
url: ...,
// type: get,
// ^^ No need for this, method: 'get' is default
},
buttons: [
{
text: '<i class="fa fa-plus" aria-hidden="true"></i>',
action: function () {
// You have to use the "table" variable here below
table.row.add({
"id": "",
"title": "t100",
"order": "100",
"mimeType": "101",
"thumpnailMimeType": "102",
"height": "103",
"width": "104"
});
table.draw();
},
},
]
});
Solution 2:[2]
I think we can't do it because it doesn't have any solution, but I can destroy (table.destroy();) the table and create a new DataTable without ajax, processing and serverSide attributes. Then call table.draw() after add new row.
For example:
table.destroy();
table = $("#example").DataTable({
// same options without ajax, processing and serverSide
});
// TODO add new row
table.draw();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Voorie |
| Solution 2 |

