Unable to load json data into datatable
Unable to load json data into datatable
Rakesh Kotian
Posts: 4Questions: 1Answers: 0
In the django app im using i have the datatable intialized as follows:
myTable = $('#table').DataTable({
ajax: {
"type": "GET",
"url": "{% url 'ProjectQuota' %}"
},
columns: [
{ 'data': 'name' },
{ 'data': 'position' },
{ 'data': 'class' },
]
});
The html of table is:
<table id="table" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Class </th>
</tr>
</thead>
</table>
The view url ProjectQuota
(as mentioned in above datatable initialization) of the django backend returns the following response:
{
"data": [
{
"name": "GINNIS",
"position": "1",
"class": "3"
},
{
"name": "FSS",
"position": "2",
"class": "4"
},
{
"name": "ASR",
"position": "1",
"class": "4"
}
]
}
When i load the webpage, im getting the following error in the console of the browser:
jquery.dataTables.js:4743 Uncaught TypeError: Cannot read property 'length' of undefined
at jquery.dataTables.js:4743
at callback (jquery.dataTables.js:3864)
at Object.success (jquery.dataTables.js:3894)
at fire (jquery-3.3.1.js:3268)
at Object.fireWith [as resolveWith] (jquery-3.3.1.js:3398)
at done (jquery-3.3.1.js:9305)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.js:9548)
Note : datatable version is : 1.10.19
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
Looks like that should work. Is the JSON response you posted copied from the browser's Network Inspector?
Are you JSON encoding the data for the Ajax response?
Kevin
@kthorngren the response i have posted is the print of response in django backend.
I'm not "JSON encoding the data for the Ajax response"
You will need to use the function that Django has to return JSON data. Maybe JsonResponse. The Ajax docs explain what Datatables expects.
Kevin
@kthorngren I have updated my code with json encoding as you mentioned from django json encoding
The backend code is as follows now:
But still facing the same issue.
Not very familiar with Django but what is
projectQuota
in the returned responsereturn Response(projectQuota)
?Should the statement be
return Response(results)
?Use the browser's network inspector to see what is returned. Steps can be found in this technote.
Kevin
Thanks for pointing
Response(projectQuota)
. This was the issue. actually theprojectQuota
is a variable which is not having key asdata
which datatable is expecting. Sorry for this mistakeThe following updated code is working fine
Thanks a lot for the support.