Dynamic Columns and Table Headers from server-side processed JSON
Dynamic Columns and Table Headers from server-side processed JSON
shibin.pb
Posts: 1Questions: 0Answers: 0
Dear Team,
I wanted to generate dynamic columns from the JSON response of server processed PHP file. Instead of defining columns
in data table script I want to load these columns from the server processed JSON file. Also wanted to load these dynamic column names as table headers.
$('#tableName').DataTable({
'processing': true,
'serverSide': true,
'searching': true,
'ordering': false,
'paging': true,
'pageLength': 10,
'serverMethod': 'post',
'ajax': {
'url': 'ajax-URL.php' ,
'dataSrc': function(json) {
return json.aaData;
}
},
'columns': [
{ data: 'empId' },
{ data: 'empName' },
{ data: 'empDesgn' },
{ data: 'deptName' },
{ data: 'epicNo' },
{ data: 'baseValidity' },
{ data: 'epicValidity' }
],
"fnDrawCallback": function (oSettings) {
var response = oSettings.json;
//console.log(response);
}
});
Please find the server side response JSON below.
{
"draw": 1,
"iTotalRecords": 322,
"iTotalDisplayRecords": 322,
"aoColumns": [
{
"name": "Emp ID",
"data": "empId"
},
{
"name": "Name",
"data": "empName"
},
{
"name": "Department",
"data": "deptName"
},
],
"aaData": [
{
"empId": "502",
"empName": "Vijayakumar T T",
"deptName": "OPT"
},
{
"empId": "132",
"empName": "Rohit Sharma",
"deptName": "OPT"
},
{
"empId": "133",
"empName": "Tony John K",
"deptName": "OPT",
},
{
"empId": "134",
"empName": "Boney Varghese",
"deptName": "OPT",
}
]
}
Please help me out to fix this Issue
Replies
I'm not sure what you're trying to do there, as you've specified data that isn't in the response, namely:
This thread should help though, it's asking the same thing.
Cheers,
Colin
@colin I have similar doubt; instead of listing hardcoded table headers <tr> in HTML,
can column headers be defined within
ajax
block, similar to 'dataSrc' function?this will help in rendering data from different sources & render the table-headers dynamically based on the data returned by the serverside.
See this FAQ and this example from this thread.
Kevin
thank you @kthorngren
also found similar ref: dynamic table header from server side processing
sample snippet
The Example under http://live.datatables.net/huyexejo/1/edit is not working ...
@dtneuling Looking at the browser's console this error appears:
Commenting out this statement fixes the issue:
https://live.datatables.net/huyexejo/1816/edit
Kevin