coder7 coder7 - 3 years ago 408
Javascript Question

jQuery DataTables: Uncaught TypeError: Cannot read property 'length' of undefined

Code: On click of the submit button, once users enter the text, the application hits the rest API which has data in the format of JSON.The code should process the JSON data and from a jquery data table.

$(document).ready(function() {
$('#txt').click(function () {
var requestData = $('#txtid').val();
var url = '<my api url>' + requestData;
$('#resultDiv1').dataTable({
"processing": true,
"ajax": url,
"columns": [
{"": "account.id"},
{"": "account.rel"},
{"": "account.fin"},
{"": "account.date"}
],
"dom": "Bfrtip",
"buttons": [
'copy', 'csv', 'excel', 'pdf', 'print'
]
});
});
});


I am trying to form a Jquery data table from a restful API but getting the below error:

Uncaught TypeError: Cannot read property 'length' of undefined
at jquery.dataTables.min.js:48
at i (jquery.dataTables.min.js:35)
at Object.success (jquery.dataTables.min.js:35)
at fire (jquery-1.12.4.js:3232)
at Object.fireWith [as resolveWith] (jquery-1.12.4.js:3362)
at done (jquery-1.12.4.js:9840)
at XMLHttpRequest.callback (jquery-1.12.4.js:10311)


Ajax Response: Here is the format of Ajax coming from RestAPI:

{
"account": [
{
"id": "1",
"rel": "P",
"fin": "abc",
"date": "2001-01-05"
},
{
"id": "2",
"rel": "P",
"fin": "def",
"date": "2001-02-05"
},
{
"id": "3",
"rel": "R",
"fin": "ghi",
"date": "2019-01-05"
}
]
}


Can someone please throw light on why this is coming and what changes do I need to make?

Answer Source

Change your initialization options as follows:

$('#resultDiv1').dataTable({
    // ... skipped other options ...
    "ajax": {
       "url": url,
       "dataSrc": "account"
    },
    "columns": [
        {"data": "id"},
        {"data": "rel"},
        {"data": "fin"},
        {"data": "date"}
    ]
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download