DataTables Cannot read property 'length' of undefined - javascript

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.

Related

datatable warning 4 - Requested unknown parameter '0' for row 0, column 0

I am working on datatable and facing this error :
DataTables warning: table id=table - Requested unknown parameter '0'
for row 0, column 0.
I have studied this link and it says that my table column defines in HTML doesn't match with the columns received from server. BUT in my case both are same.
Here is my HTML code :
<table id="table" class="display responsive nowrap" cellspacing="0" width="100%">
<thead style="background-color:#303641;">
<tr>
<th>aNumber</th>
<th>bNumber</th>
<th>cellID</th>
<th>dateTime</th>
<th>duration</th>
<th>imei</th>
<th>imsi</th>
<th>operatorId</th>
<th>mscId</th>
<th>fileId</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Datatable javascript code :
var dataTable = $('#table').DataTable({
"processing": true,
"serverSide": true,
"bFilter": false,
"iDisplayLength": configData,
dom: 'Bfrtip',
buttons: ['colvis', 'print', 'csv', 'excel', 'pdf'],
searching: false,
language: {
buttons: {
colvis: 'Show/Hide Columns'
}
},
"ajax": {
url: "getAdvanceCallAnalysisData.json",
data: function(d) {
return $.extend({}, d, {
"offset": 0,
"newRequest": newReq,
"totalRecords": total,
"lookInCol": "aNumber",
"lookInVal": "43543543",
"fromDate": from_date,
"toDate": to_date,
"callingCellId": "",
"CalledCellId": "",
"cdrType": "",
"smsType": "",
"durationFilter": "",
"selectColumns": "",
"sortCol": "",
"sortType": "",
});
},
type: "POST",
error: function() {
alert("error");
},
complete: function(data) {
total = data.responseJSON.recordsTotal;
newReq = 0;
test(total, newReq);
$("#loading_image").hide();
$(".show_datatable").show();
},
"aoColumns": [{
"mData": "aNumber"
}, {
"mData": "bNumber"
}, {
"mData": "cellID"
}, {
"mData": "dateTime"
}, {
"mData": "duration"
}, {
"mData": "imei"
}, {
"mData": "imsi"
}, {
"mData": "operatorId"
}, {
"mData": "mscId"
}, {
"mData": "fileId"
}]
}
});
you can see that my columns name and numbers match with the columns define in ajax response.
I have done same thing for another table and it was working fine but it shows error here. don't know why !!
json response : (It returns 15 records, I posted only two just to make it short)
{"msg":null,"code":null,"status":null,"data":[{"aNumber":"343","bNumber":"3434","cellID":"410-01-831-14770","dateTime":"2017-08-23 17:27:54.0","duration":419,"imei":"22380831696837","imsi":"35340311428389","operatorId":4,"mscId":"5","fileId":"4"},{"aNumber":"3434","bNumber":"5656","cellID":"410-07-1314-28271","dateTime":"2017-08-23 22:02:15.0","duration":785,"imei":"49776303943255","imsi":"35722667519554","operatorId":1,"mscId":"2","fileId":"5"}],"draw":1,"limit":1000,"recordsFiltered":12,"recordsTotal":12}
The most funny part is it shows the correct records and pagination even it display correct rows (with empty data) in datatable. This ajax call returns 15 records. Please see the image below :
Any idea, what is wrong here ?

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!

Unable to display data using jQuery datatables, AJAX and JSON

I'm having a problem displaying my data on my jQuery DataTable using AJAX. I'm using the library from datatables.net. I've tried packaging the JSON in many different formats and nothing is working. I've also messed around with the 'columns' section, interchanging 'title' and 'data.' I only have one event to display for now, but the bottom of the table shows something crazy like 4,000 entries. Here is my code:
<script src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#myTable').DataTable({
"processing": true,
"ajax": {
"url": "/api/EventsApi/GetAll",
"dataSrc": ""
},
columns: [
{ title: "Title" },
{ title: "Template" },
{ title: "Capacity" },
{ title: "Boarding Location" },
{ title: "Status" },
{ title: "Edit / Delete" }
//{ "data": "title" },
//{ "data": "eventTemplateID" },
//{ "data": "locomotive.capacity" },
//{ "data": "boardingLocationStart.city" },
//{ "data": "status" },
//{ "data": "status" }
]
});
});
<div class="title-content">#ViewBag.Title</div>
<div id="dataTable">
<table id="myTable" class="table table-hover" style="text-align: center;">
<tbody id="tBody">
<!-- Table body data goes here -->
</tbody>
</table>
</div>
Here is the JSON that's being returned from the AJAX call:
{"data":[{"tripEventID":1,"extraDetails":"this train has special details","eventName":"ZombieTrainEventName ","departureDate":"\/Date(1443715200000)\/","returnDate":"\/Date(1443718800000)\/","eventCapacityOveride":100,"eventTemplateID":3,"title":"The Zombie Train ","companyID":1,"description":"description of zombie train ride ","boardingClosed":30,"status":1,"boardingLocationStart":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationStartTo":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationReturnFrom":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"boardingLocationReturnTo":{"boardingLocationID":3,"companyID":1,"name":"Skunk Train Willits","streetAddress":"Willits somewhere","city":"Some city","state":"CA","zip":"95713","description":"Desc field1"},"allowFlexableReturnDate":false,"product":[],"productBundle":[{"bundleID":10,"companyID":1,"displayName":" Pumkin Bundle copy Test","price":0.0100,"tax":0.0200,"productList":[]}],"locomotive":{"trainID":1,"companyID":1,"title":"Skunk_Steam ","type":1,"description":"Steam locomotive ","capacity":998,"status":0},"media":{"mediaID":1,"companyID":1,"hero":[],"gallery":[{"mediaDetailID":6,"formatTypeID":2,"fileName":"testimage6.txt","order":1,"path":null,"url":null},{"mediaDetailID":7,"formatTypeID":2,"fileName":"testimage6.txt","order":1,"path":"path6","url":"url6"},{"mediaDetailID":8,"formatTypeID":2,"fileName":"testimage7.txt","order":1,"path":"path7","url":"url7"}],"inside":[{"mediaDetailID":1,"formatTypeID":1,"fileName":"testimage.txt","order":1,"path":null,"url":null},{"mediaDetailID":2,"formatTypeID":1,"fileName":"testimage2.txt","order":1,"path":null,"url":null},{"mediaDetailID":3,"formatTypeID":1,"fileName":"testimage3.txt","order":1,"path":null,"url":null}]},"duration":15,"isExclusive":false,"timeAtDestination":45,"isOneWay":false}]}
Like I said, I've tried repackaging the JSON as nested objects and arrays with nothing working. Am I missing something obvious? Any help is appreciated, thank you!
You have to name the columns in your js like the json index keys like this:
$(document).ready(function() {
$('#myTable').DataTable( {
"ajax": "path/to/your/file.json",
"columns": [
{ "data": "title" },
{ "data": "eventTemplateID" },
{ "data": "eventCapacityOveride" },
{ "data": "boardingLocationStart.streetAddress" },
{ "data": "status" },
{ "data": null }
],
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
} );
Note that you can define custom data in tables with the columnDefs option.
And than edit your HTML with something like this:
<table id="myTable" class="table table-hover" style="text-align: center;">
<thead>
<tr>
<th>Title</th>
<th>Template</th>
<th>Capacity</th>
<th>Boarding location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Title</th>
<th>Template</th>
<th>Capacity</th>
<th>Boarding location</th>
<th>Status</th>
<th>Edit / Delete</th>
</tr>
</tfoot>
</table>
Here you can find a working fiddle

server side data loading from C# in jquery datatable

Hi i have successfully implemented jquery data table server side call,but i am unable to load data in html view
it just says processing
here is my Js code
$('#internetTable').dataTable({
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': 'api/values/GetInternetSales'
"aoColumns": [
{ "mData": "Calls" },
{ "mData": "LevelOneOperators" },
{ "mData": "LevelTwoOperators" },
{ "mData": "Issueraised" },
{ "mData": "SalesDate" },
{ "mData": "AutomaticResponses" }
]
});
and this is html code
<table id="internetTable" class="table table-bordered table-hover">
<thead>
<tr>
<th >Date</th>
<th>Issue Raised</th>
<th>Level One Operators</th>
<th >Level Two Operators</th>
<th>Automatic Responses</th>
<th>Calls</th>
</tr>
</thead>
</table>
And the response am getting from server is
{"sEcho":"2","iTotalRecords":10,"iDisplayStart":1,"iDisplayEnd":1,"iDisplayLength":10,"iTotalDisplayRecords":100,"InternetDataList":[{"Calls":"320","LevelOneOperators":"1","LevelTwoOperators":"7","Issueraised":"1","SalesDate":"2010-11-25T00:00:00","AutomaticResponses":235}]}
Now,just want to ask that what modifications in JS code do i need to do to parse it in table,as i have searched alot but could'nt get any solution.
Got the answer i need to add following code in js:
$('#internetTable').dataTable({
'bProcessing': true,
'bServerSide': true,
"sServerMethod": "GET",
// to enable Pagination
"sPaginationType": "full_numbers",
'sAjaxSource': 'api/values/GetInternetSales',
"sAjaxDataProp": "InternetDataList",
"aoColumnDefs": [{
"mData": "InternetDataList"
}],
"aoColumns": [
{ "mData": "Calls" },
{ "mData": "LevelOneOperators" },
{ "mData": "LevelTwoOperators" },
{ "mData": "Issueraised" },
{ "mData": "AutomaticResponses" },
{ "mData": "SalesDate" }
]
});
As,here the sAjaxDataProp is your data name as in my case it is InternetDataList and default it is aadata

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