DataTable shows zero rows even get the response - javascript

I have a datatable.I tried to load via ajax .The response contain data but it shows no data found.My code is given below
<table id="user_list_table">
<thead>
<tr>
<th>name</th>
<th>phone</th>
<th>email</th>
<th>address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
My js contains
$(document).ready(function() {
var MY_AJAX_ACTION_URL = "/social/index.php?id=4&userform[action]=datatable&userform[controller]=User";
$('#user_list_table').dataTable({
"autoWidth": false,
"bPaginate": false,
"searching": false,
"ordering": true,
"oLanguage": {
"sZeroRecords": "No data Found",
"sProcessing": 'processing'
},
"bInfo": false,
"aoColumns": [
{'mData':'name','bSortable': true},
{'mData':'phone','bSortable': true},
{ 'mData':'email','bSortable': true },
{ 'mData':'address','bSortable': true}
],
"sAjaxDataProp": "",
"bProcessing": true,
"bServerSide": true,
"sAjaxSource":MY_AJAX_ACTION_URL
});
});
I got the following response
{"iTotalRecords":2,"iTotalDisplayRecords":{"data":[{"name":"xyz","phone":"678654454","email":"xyz#gmail.com","address":"ytruye"},{"name":"abc","phone":"678654454","email":"abc#gmail.com","address":"ytruye"}]}}

The server response is a little bit missed up. You have
{
"iTotalRecords": 2,
"iTotalDisplayRecords": {
"data": [
but iTotalDisplayRecords is supposed to be the number of filtered records (and iTotalRecords of course the total number of records). If you correct the response to
{
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"data": [
{
and remove "sAjaxDataProp": "", then it works -> http://jsfiddle.net/2o6eLt2z/
So the problem is serverside, there is no possible way to correct the problem clientside since the JSON will never work with dataTables as a serverside source. You could use the serverscript in an ajax: { url: ...} and return the corrected JSON in the dataSrc callback, but it seems to me you want to use serverside processing.

Related

How to reload table data using DataTables, Ajax call & Json response?

I have a table that is generated through Thymeleaf. I would like to refresh the contents of the table using jQuery.
<table class="table table-hover" id="main-table">
<thead class="thead-inverse">
<tr>
<th class="col-md-2 text-center">Network Id</th>
<th class="col-md-2 text-center">Rep date</th>
<th class="col-md-2 text-center">Hashrate [KH/s]</th>
</tr>
</thead>
<tbody>
<tr th:each="networkHashrate : ${networkHashrates}" th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'">
<td class="text-center" id="hashrateId" th:text="${networkHashrate.id}"> Sample id</td>
<td class="text-center" id="repDate" th:text="${#findAndDisplayDataService.formatDate(networkHashrate.repDate)}">Sample rep-date</td>
<td class="text-center" id="hashrate" th:text="${#findAndDisplayDataService.formatHashrate(networkHashrate.hashrate)}">Sample hashrate</td>
</tr>
</tbody>
</table>
I have come up with such function to update table contents every 8s:
$(document).ready(function() {
var table = $('#main-table').DataTable({
ajax: {
url: '/refresh',
dataSrc:''
},
paging: true,
lengthChange: false,
pageLength: 20,
stateSave: true,
info: true,
searching: false,
"aoColumns": [
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "asc", "desc" ] },
{ "orderSequence": [ "desc", "asc" ] }
],
"order": [[ 0, "asc" ]]
});
setInterval(function(){
table.ajax.reload();
}, 8000);
});
Here's the JSON response:
[{
"id":1,
"repDate":{
"offset":{ },
"nano":880042000,
"year":2018,
"monthValue":4,
"dayOfMonth":25,
"hour":12,
"minute":58,
"second":53,
"month":"APRIL",
"dayOfWeek":"WEDNESDAY",
"dayOfYear":115
},
"hashrate":5114926.0
},...more entries
]
An empty table prints and I keep getting an error:
Uncaught TypeError: Cannot read property 'reload' of undefined
There's also an alert pop-up saying:
Data Tables warning: table id=main-table - Requestem unknown parameter '0' for row 0 column 0. For more information about this error, please see: http://datatables.net/tn/4
EDIT
I moved table declaration outside the function. Now I just keep getting the warning.
EDIT 2
I did as you stated, the data keeps refreshing, but there are still few issues.
First of all, my stateSave: true property stopped working, so when the table is reloaded it always gets back to the first page.
Secondly, I lost all my styling (class="text:center" for example) and on:click property that were originally in my html file.
Try to declare the table before the $(document).ready :
var table;
$(document).ready(function() {
table = $('#main-table').DataTable({"serverSide": true, ...})
setInterval(function(){
table.ajax.reload();
}, 8000);
})
The error is related to your column definition, try this way to define columns :
"columnDefs": [
{
"targets": 0,
"data": "id",
},
{
"targets": 1,
"data": "repDate",
},
{
"targets": 2,
"data": "repDate",
}
]

Jquery Datatables ajax call won't run

I have following dataTables jquery in my js file
$("#manage_chauffeurs").dataTable({
"processing": true,
"bServerSide": true,
"aaSorting": [],
"ajax":{
'type': 'POST',
'url': '/admin/reports/chauffeurs_data'
},
"responsive": true,
"aoColumnDefs": [
{ 'bSortable': false, 'aTargets': [ 14 ] }
],
"columnDefs": [ { targets: '_all', visible: true } ],
"dom": '<"top"f>rt<"bottom"p><"clear">',
"aoColumns": [
{ "mDataProp": "name", "sDefaultContent": "", "sClass": "center_align"},
{ "mDataProp": "user_id", "sDefaultContent": "", "sClass": "center_align" }
]
});
Below is the html
<table class="display responsive no-wrap" id="manage_chauffeurs">
<thead>
<tr>
<th width="50%">User Name</th>
<th width="50%">User ID</th>
</tr>
</thead>
</table>
I have the resource '/admin/reports/chauffeurs_data' set at my server. However, I don't get an ajax call. No call at all.
Browser console gives the following error:
jquery.dataTables.js?body=1:4090 Uncaught TypeError: Cannot read property 'style' of undefined
Checked for above error, I have no mismatch of columns in my code.
What could be going wrong here?
Someone please help!

DataTables Cannot read property 'length' of undefined

Below is the document ready function
Script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$('#example').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "GetUser.ashx",
"sServerMethod": "POST",
"sAjaxDataProp" : "",
"aoColumnDefs": [ {
"aTargets": [ 0 ],
"mData": "download_link",
"mRender": function ( data, type, full ) {
return 'Detail';
}
} ],
"aoColumns": [
{ "mData": "LoginId" },
{ "mData": "Name" },
{ "mData": "CreatedDate" }
]
});
Below is the respond from server (GetUser.ashx)
[
{
"UserId": "1",
"LoginId": "white.smith",
"Activated": "Y",
"Name": "Test Account",
"LastName": "Liu",
"Email": "white.smith#logical.com",
"CreatedDate": "1/21/2014 12:03:00 PM",
"EntityState": "2",
"EntityKey": "System.Data.EntityKey"
},
More Data...
]
Below is the html table where the data should be put
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
<tr>
<th width="15%">User Detail</th>
<th width="15%">LoginID</th>
<th width="15%">Name</th>
<th width="15%">Created Date</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
<tfoot>
<tr>
<th width="15%">User Detail</th>
<th width="15%">LoginID</th>
<th width="15%">Name</th>
<th width="15%">Created Date</th>
</tr>
</tfoot>
</table>
Expected result:
But I came across a problem:
While the page is loading, there was an uncaught exception from the browser:
Cannot read property 'length' of undefined
When I further check, it came from line 2037 of jquery.dataTables.js
var aData = _fnGetObjectDataFn( oSettings.sAjaxDataProp )( json );
I checked that the json was valid, but the "aData" was null, why this happen?
Your "sAjaxDataProp" : "" is set to an empty string, which causes this error.
dataTables expects to have a string here to tell under which key your server returned data can be found.
This defaults to aaData, so your json should include this key amongst all others that might be returned or needed by pagination etc.
Normal serversided json:
{
"iTotalRecords":"6",
"iTotalDisplayRecords":"6",
"aaData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],...
Since all values are in aaData you don't need sAjaxDataProp at all.
Modified serverside json:
{
"iTotalRecords":"6",
"iTotalDisplayRecords":"6",
"myData": [
[
"1",
"sameek",
"sam",
"sam",
"sameek#test.com",
"1",
""
],
Now the values are in myData. so you need to tell dataTables where to find the actual data by setting:
"sAjaxDataProp" : "myData"
Here is a Plunker
As there are 4 columns, add the following in "aoColumns":
"aoColumns": [
{ "mData": null }, // for User Detail
{ "mData": "LoginId" },
{ "mData": "Name" },
{ "mData": "CreatedDate" }
]
For undefined length, I have tried the following code and it's working:
$('#example').dataTable({
"aLengthMenu": [[100, 200, 300], [100, 200, 300]],
"iDisplayLength": 100,
"iDisplayStart" : 0,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "GetUser.ashx",
"sServerMethod": "POST",
"sAjaxDataProp" : "",
"aoColumnDefs": [ {
"aTargets": [ 0 ],
"mData": "download_link",
"mRender": function ( data, type, full ) {
return 'Detail';
}
} ],
"aoColumns": [
{ "mData": null },
{ "mData": "LoginId" },
{ "mData": "Name" },
{ "mData": "CreatedDate" }
]
});
The reference site to know more about aLengthMenu is:
https://legacy.datatables.net/ref#aLengthMenu
If you see this error, look at the json returned from the server, and then make sure that all of your datatable 'mData' values have matching entry. If you are also using a bean, check there as well.
And there is no need specify 'tr', 'td', etc for the table. It is much cleaner if you let jquery do that for you. Here is what my tables look like:
<table cellpadding="0" cellspacing="0" border="0" class="display" id="myTable" style="table-layout:fixed" ></table>
and then my datatable elements specify the width and column title:
{sTitle: "Column A", sWidth: "100px", mData: "idStringFromJson", bSortable: false},
Use $('#example').DataTable({.. (capital D) instead of $('#example').dataTable({..
When I ran into this problem, it was actually the result of an un-applied migration. I had restored a backup of the database, which hadn't yet had one of my recent schema migrations run on it, and once I ran migrations, everything worked fine.

Datatable render after AJAX call

I am trying to render a data table by making an AJAX call getting some data from controller and then writing data table. sData['id'] is just a number
Here is my code:
$.post('/admin/user_groups_data/' + sData['id']).done(function(data) {
$('#user_groups_table').dataTable({
"bProcessing": true,
"bDeferRender": true,
"sPaginationType": "full_numbers",
"aaData": data, // data here is a JSON object, shows on Firebug correct data and fields
"aoColumns": [
{ "mData": "id"},
{ "mData": "title" },
{ "mData": "category" },
]
});
});
Below is my HTML code
<table id="user_groups_table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Type</th>
</tr>
</thead>
</table>
It seems like the data table gets rendered first even before AJAX call is done so it gives me error
DataTables warning (table id = 'user_groups_table'): Requested unknown parameter 'id' from the data source for row 0
I have the .done at top but seems like it doesn't even respect that. Any help would be great. thx
Just added sAjaxSource to it and it works now, seems like the $.post had not completed yet when data table was being written, sAjaxSource retrieves the data and brings it back and then writes data table.
var oTable = $('#user_groups_table').dataTable({
"bDestroy": true,
"bProcessing": true,
"bDeferRender": true,
"sPaginationType": "full_numbers",
//"aaData": data,
"sAjaxSource": '/admin/user_groups_data/' + sData['id'],
"aoColumns": [
{ "mData": "group_id", "bVisible": false},
{ "mData": "title" },
{ "mData": "category" },
]
});

jquery datatables: adding extra column

Scenario
I am using datatables (#version 1.9.4) for the first time to display data to the user.
I succeed in retrieving the data via ajax and in binding them to the datatable.
Now I want to add extra columns to let the user process the records. For semplicity sake, the aim is to add a button with an onclick handler that retrieve the data of the 'clicked' record.
In my plan I would bind the json item corresponding to the 'clicked' record to the onclick handler.
Till now, if I add an additional TH for the action column to the DOM, an error occurs from datatables code:
Requested unknown parameter '5' from data source for row 0
Question
How to set custom columns? How to fill their content with HTML?
Here is my actual config.
HTML
<table id="tableCities">
<thead>
<tr>
<th>country</th>
<th>zip</th>
<th>city</th>
<th>district code</th>
<th>district description</th>
<th>actions</th>
</tr>
</thead>
<tbody></tbody>
</table>
Javascript
$('#tableCities').dataTable({
"bPaginate": true,
"bLengthChange": false,
"bFilter": true,
"bSort": true,
"bInfo": false,
"bAutoWidth": true
, "bJQueryUI": true
, "bProcessing": true
, "bServerSide": true
, "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});
Sample Json result
{
"aaData":
[
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino"
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino"
]
],
"iTotalRecords": 2,
"iTotalDisplayRecords": 2,
"iDisplayStart": 0,
"iDisplayLength": 2
}
Edit
Daniel is right. The solution is to set up the custom column in the aoColumnDefs, specifying the mData and the mRender properties. In particular mRender lets to define custom html and javascript.
/* inside datatable initialization */
, "aoColumnDefs": [
{
"aTargets": [5],
"mData": null,
"mRender": function (data, type, full) {
return 'Process';
}
}
]
You can define your columns in a different way
like this
"aoColumns": [
null,
null,
null,
null,
null,
{ "mData": null }
]
or this
"aoColumnDefs":[
{
"aTargets":[5],
"mData": null
}
]
Here some docs Columns
Take a look at this DataTables AJAX source example - null data source for a column
Note that prior to DataTables 1.9.2 mData was called mDataProp. The name change reflects the flexibility of this property and is consistent with the naming of mRender. If 'mDataProp' is given, then it will still be used by DataTables, as it automatically maps the old name to the new if required.
Another solution/workaround could be adding that '5' parameter...
For example adding extra "" to each row
like this:
[
"IT",
"10030",
"VILLAREGGIA",
"TO",
"Torino",
""
],
[
"IT",
"10030",
"VISCHE",
"TO",
"Torino",
""
]
Just in case anyone using a newer version of DataTables (1.10+) is looking for an answer to this question, I followed the directions on this page:
https://datatables.net/examples/ajax/null_data_source.html
Posting this answer here, just to show that where the aoColumnDefs needs to be defined. I got help from this question it self, but I struggled for a while for where to put the aoColumnDefs. Further more also added the functionality for onclick event.
$(document).ready(function() {
var table = $('#userTable').DataTable( {
"sAjaxSource": "/MyApp/proctoring/user/getAll",
"sAjaxDataProp": "users",
"columns": [
{ "data": "username" },
{ "data": "name" },
{ "data": "surname" },
{ "data": "status" },
{ "data": "emailAddress" },
{ "data" : "userId" }
],
"aoColumnDefs": [
{
"aTargets": [5],
"mData": "userId",
"mRender": function (data, type, full) {
return '<button href="#"' + 'id="'+ data + '">Edit</button>';
}
}
]
} );
$('#userTable tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
console.log(data);
$('#userEditModal').modal('show');
});
} );

Categories

Resources