I am getting the following error when trying to load DataTables ajax sourced data:
DataTables warning: table id=report-table - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Below is my DataTables html:
<table id="report-table" class="display nowrap" style="width:100%">
<thead>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Page ID</th>
<th>Schema</th>
<th>Name</th>
<th>Last Modified</th>
<th>Last Modified User</th>
</tr>
</tfoot>
</table>
Below is my DataTables javascript:
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
Below is the confirmed json my C# controller is returning for the DataTables ajax data:
{
"data":[
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
},
{
"PageId":"foo",
"SchemaName":"foo",
"Name":"foo",
"LastModified":"foo",
"LastModifiedUser":"foo"
}
]
}
The error seems to be related to the JSON format, but not sure what is wrong?
EDIT:
Adding full javascript code:
<script>
$(function () {
$("button#report-form-submit").click(function () {
event.preventDefault();
var data = $("form#report-form").serialize();
$.ajax({
type: "POST",
url: "@Url.Action("GetReportJson", "Report")",
data: data,
dataType: 'json',
beforeSend: function (data) {
},
success: function (data) {
// Report DataTables Init
// ===========================================
$('#report-table').DataTable({
"ajax": data,
"columns": [
{
"data": "PageId",
"orderable": true
},
{
"data": "SchemaName",
"orderable": false
},
{
"data": "Name",
"orderable": true
},
{
"data": "LastModified",
"orderable": true
},
{
"data": "LastModifiedUser",
"orderable": true
},
],
"order": [[3, "desc"]]
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function (data) {
}
});
});
});
</script>
3
Answers
the data source should be an array of arrays that contains the data in the tbody
say
see the example [https://datatables.net/examples/data_sources/js_array.html][1]
additionally, use
data: data.data
instead of"ajax" : data
As your JSON response is an object but not an array, specify the
ajax
to get theJsonResponse.data
as below:OR
Updated: Change from
json.data
todata
as Post Owner changed requirement.Reference
ajax – DataTables.net
Your
<script>
block should look like this to initialize your data for your Data Tables: