i have spend several hours trying to find how to populate the datatables with a json that comes from the backend, here is my code:
1) Create your datatable on document.ready.
2) Send a ajax request to get json data.
3) Inside the loop, instead of creating <tr>
elements use datatables fnAddData();
function. like -
$('#dataTables-example').dataTable().fnAddData([first-columnval, second-columnval, etc]);
I have created a sample
HTML
<button id="addData">Add Data</button>
<table id="dataTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS
$(document).ready(function() {
//creating a temp json. you will get this from server side after ajax call
var jsonString = '[{"Id": 1,"Title": "Title1","Summary": "Summary1" },{"Id": 2,"Title": "Title2","Summary": "Summary2"}]';
$("#addData").click(function(){
var data = JSON.parse(jsonString);
for(i=0; i<data.length;i++) {
$('#dataTable').dataTable().fnAddData([
data[i].Id,
data[i].Summary,
data[i].Title
]);
}
//console.log(JSON.parse(jsonString));
});
function createDatatable() {
$('#dataTable').dataTable({
bFilter: false,
bLengthChange: false,
"sDom": 'lfrtip',
pagingType: 'full',
"oLanguage": {
"oPaginate": {
"sFirst": "<b><<</b>",
"sLast": "<b>>></b>",
"sNext": "<b>></b>",
"sPrevious": "<b><</b>"
}
}
});
}
createDatatable();
});
Please check this Fiddle