i have one-to-many related data (th and td) and on page load i load the data from the server with ajax, how can i select each th (column) and populate it with data linked to it.
this is the table:
<table border="1" style="width: 95%;" id="table">
<tr id="ths">
{% for th in ths %}
<th>
<div data-th_id="{{ th.id }}">{{ th.name }}</div>
</th>
{% endfor %}
</tr>
<!-- populate with AJAX -->
<!-- <tr>
<td>
<div></div>
</td>
</tr> -->
<!-- END AJAX -->
</table>
AJAX:
$("table tr th").each(function () {
var th_id = $(this).children().data('th_id')
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/api/load_tds",
data: JSON.stringify({
"th_id": th_id
}),
success: function (res) {
table = document.getElementById("table");
$.each(res, function (index, value) {
});
}
});
});
I hope I got you right. You want to get the data from the server for each column and then display it as <td> 's in the correct <tr>.
// creating an empty table:
for (let i = 0; i < 5/* amount of columns*/; i++) {
var $row = $('<tr/>');
for (let a = 0; a < 5/* amount of rows*/; a++) {
$row.append($('<td/>'));
}
$('table').append($row);
}
$("table tr th").each(function () {
var th_id = $(this).children().data('th_id');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/api/load_tds",
data: JSON.stringify({
"th_id": th_id
}),
success: function (res) {
let th_index = 0 /* set the index of the current column */;
// filling the nth td of each row with your data
$.each(res, function (index, value) {
$('table tr:nth-child(' + index + ') td:nth-child(' + th_index + ')').append('<div>' + value + '</div>');
});
}
});
});
Since I don't have no access to your API, I couldn't test the code, but I hope it works, or at least the principle helps you.
But if you only want to load the data on page load, from your server, it would be best practice to pass it directly trough your Jinja2 template. It minimizes data transfer and the js code would be cleaner. It is always better to process data directly on the server side into your template than to fetch it afterwards with Ajax!
Best regards