Reputation: 815
I would like to create a table with the the JSON data I retrieved from my API, but jQuery keeps putting elements in the wrong place....
This is my jQuery code:
var container = $("#container");
var table = $("#table");
$(document).ready(function() {
callAPI();
});
function callAPI() {
$.ajax({
url: "action-api.php",
method: "GET",
dataType: 'json',
success: function(data) {
console.log(data);
container.append('<table style="width:100%"><tr><th>ID</th><th>Naam</th> <th>Brouwerij</th><th>Type</th><th>Gisting</th><th>Percentage</th><th>Inkoop Prijs</th></tr>');
$.each(data, function(i, item) {
container.append('<tr><td>' + item.id + '</td>');
container.append('<td>' + item.naam + '</td>');
container.append('<td>' + item.brouwerij + '</td>');
container.append('<td>' + item.type + '</td>');
container.append('<td>' + item.gisting + '</td>');
container.append('<td>' + item.perc + '</td>');
container.append('<td>' + item.inkoop_prijs + '</td></tr>');
});
container.append('</table>');
},
});
}
This is the HTML output:
Upvotes: 2
Views: 792
Reputation: 67505
You've to create the table
and the row tr
separated of the td
, else they will be closed automatically after the append, for example when you do :
container.append('<tr><td>' + item.id + '</td>');
The output will be :
<tr><td>item.id</td></tr>
____________________^^^^^ //NOTE the closed tag will be added automatically
So you have just to separate them like :
var table = $('<table style="width:100%"></table>');
table.append('<tr><th>ID</th><th>Naam</th> <th>Brouwerij</th><th>Type</th><th>Gisting</th><th>Percentage</th><th>Inkoop Prijs</th></tr>');
$.each(data, function(i, item) {
var tr = $('<tr/>');
tr.append('<td>' + item.id + '</td>');
tr.append('<td>' + item.naam + '</td>');
tr.append('<td>' + item.brouwerij + '</td>');
tr.append('<td>' + item.type + '</td>');
tr.append('<td>' + item.gisting + '</td>');
tr.append('<td>' + item.perc + '</td>');
tr.append('<td>' + item.inkoop_prijs + '</td>');
table.append(tr);
});
container.append(table);
Hope this helps.
Upvotes: 3
Reputation: 372
Or you can just create your whole bloc and then append it :
var container = $("#container");
var table = $("#table");
$(document).ready(function() {
callAPI();
});
function callAPI() {
$.ajax({
url: "action-api.php",
method: "GET",
dataType: 'json',
success: function(data) {
console.log(data);
var html = '<table style="width:100%"><tr><th>ID</th><th>Naam</th> <th>Brouwerij</th><th>Type</th><th>Gisting</th><th>Percentage</th><th>Inkoop Prijs</th></tr>';
$.each(data, function(i, item) {
html+='<tr><td>' + item.id + '</td>';
html+='<td>' + item.naam + '</td>';
html+='<td>' + item.brouwerij + '</td>';
...
});
html+='</table>';
container.append(html);
},
});
}
Here is the explanation for this: How do I force jQuery append to NOT automatically close a tag?
Upvotes: 1