Reputation: 63
I'm trying to populate a table with a JSON file using DataTables, but every time I load up the page, the table just shows "No data available in table".
This is my current code:
<table id="table_id" class="display">
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Mail</th>
<th>Confirmado</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1</td>
<td>Row 1 Data 2</td>
</tr>
<tr>
<td>Row 2 Data 1</td>
<td>Row 2 Data 2</td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function () {
$('#table_id').DataTable({
"ajax" : {"url":"/personas.json", "dataSrc":""},
"columns" : [
{personas : "id"},
{personas : "nombre"},
{personas : "apellido"},
{personas : "email"},
{personas : "confirmado"}
]
});
});
</script>
This is a piece of the JSON code:
{
"personas": [
{
"id": 0,
"nombre": "Aurelia",
"apellido": "Osborn",
"email": "[email protected]",
"confirmado": false
},
{
"id": 1,
"nombre": "Curry",
"apellido": "Jefferson",
"email": "[email protected]",
"confirmado": true
}
]
}
And this is what I get when I load up the page (part of it):
And just in case it might be the problem, this is the directory of the JSON:
Upvotes: 0
Views: 6003
Reputation: 3653
Change
"ajax" : {"url":"/personas.json", "dataSrc":""}
to
"ajax" : {"url":"/personas.json", "dataSrc":"personas"}
By specifying dataSrc
you tell that you use personas
array from your personas.json
as your data source.
See these for reference:
https://datatables.net/examples/ajax/custom_data_property.html https://datatables.net/examples/ajax/custom_data_flat.html
Also, as was already mentioned, your array [
opening bracket doesn't have a matching ]
closing bracket.
Here's a working example with your data:
https://jsfiddle.net/onLuw2pa/165/
I've changed your JSON objects to arrays of values (by doing this you don't have to specify columns
):
{
"personas":[
[
0,
"Aurelia",
"Osborn",
"[email protected]",
false
],
[
1,
"Curry",
"Jefferson",
"[email protected]",
true
]
]
}
https://jsfiddle.net/onLuw2pa/169/ And here's an example which uses your exact JSON.
Upvotes: 4
Reputation: 363
It could be because your 'personas' data is malformed json. It is missing a closing array brace. It should be:
{
"personas": [
{
"id": 0,
"nombre": "Aurelia",
"apellido": "Osborn",
"email": "[email protected]",
"confirmado": false
},
{
"id": 1,
"nombre": "Curry",
"apellido": "Jefferson",
"email": "[email protected]",
"confirmado": true
}
]
}
Upvotes: 0