Uncaught TypeError: Cannot read property 'length' of undefined
Uncaught TypeError: Cannot read property 'length' of undefined
Hi guys,
I guess I need a steer of the following error:
Uncaught TypeError: Cannot read property 'length' of undefined
I am using the JSONServer with the structure below.
I tried various options with the datSrc. No success, yet.
"dataSrc": "mydata",
Any idea?
Many thanks in advance.
HTML
<div class="table-responsive">
<table id="table1" class="table table-striped table-sm">
<thead>
<tr>
<th>MyID</th>
<th>MyType</th>
</tr>
</thead>
</table>
JS
<script>
$(document).ready(function() {
$('#table1').DataTable({
"ajax": {
"url": "http://localhost:3000/mydata",
"type": "GET",
"dataSrc": "mydata",
"columns": [{
data: "MyID"
},
{
data: "MyType"
}
]
}
});
});
</script>
JSONServer structure
{
"mydata": [
{
"MyID": "10001",
"MyType": "Type1"
},
{
"MyID": "10002",
"MyType": "Type2"
}
]
}
Browser request
http://localhost:3000/mydata?_=1559756167604
Browser JSON structure
[
{
"MyID": "10001",
"MyType": "Type1"
},
{
"MyID": "10002",
"MyType": "Type2"
}
]
Browser error
(anonymous) @ dashboard.js:6
(anonymous) @ dashboard.js:53
jquery.dataTables.min.js:49 Uncaught TypeError: Cannot read property 'length' of undefined
at jquery.dataTables.min.js:49
at i (jquery.dataTables.min.js:35)
at Object.success (jquery.dataTables.min.js:36)
at c (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at l (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
EDIT:: Edited to use Markdown formatting.
Answers
First please try to use Markdown formatting to format your code snippets.
Looks like your server JSON structure is different than what you see at the browser? The structure you receive at the browser is what you are interested in when setting the
ajax.dataSrc
.The primary problem (and likely the cause of the error) is that you have the
columns
definition inside theajax
option. Your code should look more like this:Your
ajax.dataSrc
will either be"mydata"
or""
depending on the structure of the received JSON.Kevin
Hi Kevin,
thanks. The trick was indeed your hint with the columns outside the ajax structure.
Now it works.
Many thanks. You made my day
Case closed
Dirk