Reputation: 510
I'm trying load json data on table using datatables
The return of json from php is like this:
data = {
"CLIENTES": {
"0": {
"ID": "1",
"NOME": 'GABRIEL'
},
"1": {
"ID": "2",
"NOME": 'RODRIGUES'
}
}
}
In the documentation columns data they say that I need to follow this structure:
table.DataTable({
"ajax": url,
columns: [
{"data": "CLIENTES.ID"},
{"data": "CLIENTES.NOME"}
]
});
But dont work, and we know that the right acess to de data index is this way:
{"data": "CLIENTES['0'].ID"},
{"data": "CLIENTES['1'].ID"},
But need's to be dynamically, how can I do this?
Upvotes: 1
Views: 1306
Reputation: 4242
You should create new data for datatable without CLIENTES
.... map is an option.
$(document).ready(function() {
data = {
"CLIENTES": {
"0": {
"ID": "1",
"NOME": 'GABRIEL'
},
"1": {
"ID": "2",
"NOME": 'RODRIGUES'
}
}
};
var newData = $.map(data.CLIENTES, function(el) { return el });
$('#example').DataTable({
data: newData,
columns: [
{"data": "ID"},
{"data": "NOME"}
]
});
});
example: https://jsfiddle.net/cmedina/7kfmyw6x/5/
Upvotes: 1
Reputation: 1544
you can do things to an object dynamically by using for var in
var myArray = [] //an empty array
for(var i in data){
myData.push({"data": "CLIENTES[i].ID"})
myData.push({"data": "CLIENTES[i].NOME"})
}
then later you can do this
table.DataTable({
"ajax": url,
columns: myArray
});
but I suspect the way you write {"data": "CLIENTES[i].ID"}
is wrong, though i havent used datatables
before.
maybe something like this is more correct? it's how you usually get to object properties
for(var i in data){
myData.push({"data": data.CLIENTES[i].ID})
myData.push({"data": data.CLIENTES[i].NOME})
}
Upvotes: 0
Reputation: 1148
If you remove the 'CLIENTES' outer array and only return an array of the results in your PHP, you will be able to refer to the values like this:
table.DataTable({
"ajax": url,
columns: [
{"data": "ID"},
{"data": "NOME"}
]
});
Upvotes: 0