Issue
I have a JSON object data that am getting from an api call. How can I map it to two columns. This is the JSON Object
[
{
"id": 322,
"uploadStatus": 0,
"labName": "CS Minhewene"
},
{
"id": 323,
"uploadStatus": 0,
"labName": "CS Nacuale"
},
{
"id": 324,
"uploadStatus": 0,
"labName": "CS Mesa"
},
{
"id": 325,
"uploadStatus": 0,
"labName": "CS Metoro"
},
{
"id": 326,
"uploadStatus": 0,
"labName": "CS Ngewe"
},
{
"id": 327,
"uploadStatus": 0,
"labName": "CS Mariri"
}
]
Whenever I try to map it I get a datatable error
DataTables warning: table id=tableBody - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
This is my implementation
$.ajax({
type: 'GET',
contentType: "application/json; charset=utf-8",
url: 'api/getuploadbydistricts/'+this.name,
success: function (data) {
myJsonData = data;
console.log('data 2', myJsonData);
populateDataTable(JSON.stringify(myJsonData));
$('#tableBody').dataTable().fnDestroy();
},
error: function (e) {
console.log("There was an error with your request...");
console.log("error: " + JSON.stringify(e));
}
});
// populate the data table with JSON data
function populateDataTable(data) {
console.log("populating data table...");
console.log('data 2', data.uploadStatus);
$('#tableBody').dataTable().fnDestroy();
$("#tableBody").DataTable().clear();
$('#tableBody').dataTable().fnAddData( [
data.uploadStatus,
data.labName,
]);
// clear the table before populating it with more data
}
How can I display the json object to the datatable correctly, an help is appreciated
Solution
change your list object to list array, it should be like
data = [
[a, b],
[c, d]
]
snippet
data = [{"id":322,"uploadStatus":0,"labName":"CS Minhewene"},{"id":323,"uploadStatus":0,"labName":"CS Nacuale"},{"id":324,"uploadStatus":0,"labName":"CS Mesa"},{"id":325,"uploadStatus":0,"labName":"CS Metoro"},{"id":326,"uploadStatus":0,"labName":"CS Ngewe"},{"id":327,"uploadStatus":0,"labName":"CS Mariri"}];
// change it to list array
data = data.map(d=>[d.uploadStatus, d.labName]);
populateDataTable(data);
// populate the data table with JSON data
function populateDataTable(data) {
$("#tableBody").dataTable().fnClearTable();
$('#tableBody').dataTable().fnAddData(data);
}
<link rel="stylesheet" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
<table id="tableBody" class="display">
<thead>
<tr>
<th>uploadStatus</th>
<th>labname</th>
</tr>
</thead>
<tbody>
<tr><td>xxx</td><td>yyy</td></tr>
</tbody>
</table>
Answered By - uingtea Answer Checked By - David Marino (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.