I am trying to populate a data table using ajax call. But it fill only the first column with last value from columns
.
Here is my code:
$(document).ready(function() {
$.ajax({
url: "http://192.168.2.32:5000/get_all_locations",
'method': 'GET',
'contentType': 'application/json'
}).done(function(data) {
console.log('dataaa', data);
$('#myTable').dataTable({
'aaData': data['data'],
"columns": [{
"data": "id",
"data": "name",
"data": "code"
}]
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>Code</th>
</tr>
</thead>
</table>
In the above image, id field show value of code.
How can i resolve this?
Output of data
{…}
StatusCode: true
StatusDescription: "Location details has been pulled successfully."
data: (9) […]
0: Object { code: "1007", id: 20, is_free_zone: true, … }
1: Object { code: "1002", id: 15, is_free_zone: false, … }
2: Object { code: "1001", id: 14, is_free_zone: false, … }
3: Object { code: "1003", id: 16, is_free_zone: false, … }
4: Object { code: "1004", id: 17, is_free_zone: false, … }
5: Object { code: "1006", id: 19, is_free_zone: false, … }
6: Object { code: "1005", id: 18, is_free_zone: false, … }
7: Object { code: "1008", id: 21, is_free_zone: false, … }
8: Object { code: "1009", id: 22, is_free_zone: false, … }
length: 9
3
Answers
See https://datatables.net/examples/ajax/objects.html
Each column should be a separate object with a data property pointing to the name of the property on the record.
Your column def is an object instead of an array of objects.
Each column config needs a
data
field and an optionaltitle
.Change your code as follow
you can customise each column by adding filtring or enabling search :