i create datatable, i want create dynamically columns data.
my init datatable looks like this :
var columnsData = [
{data: 'name'},
{data: 'phone'}
];
var dtable = $('#dtable').DataTable({
serverSide : true,
ajax : '/data',
columns : columnsData,
});
in some condition, make columns data changed. i don't have solution for that.
example columns what i want to change :
columnsData = [
{data: 'name'},
{data: 'address'}
]
i was try
dtable.columns.data( columnsData ).load();
dtable.columns.data( columnsData ).draw();
but still doesn't work.
CodePudding user response:
You can use the below function to recreate the data table with changes in structure.
function getDT() {
$.ajax({
url: '/data',
success: function (data) {
data = JSON.parse(data);
columnNames = Object.keys(data.data[0]);
for (var i in columnNames) {
columns.push({data: columnNames[i],
title: capitalizeFirstLetter(columnNames[i])});
}
$('#dtable').DataTable( {
processing: true,
serverSide: true,
ajax: '/data',
columns: columns
} );
}
});
}
please find the complete implementation on Example