I have a page that makes an Ajax call to a database on page load. It returns a list of companies that the user is following and then iterates the list trough and does another Ajax call to each company, to get some statistics about them. The statistics are then added to a Datatable which is being drawn quite a few times:
var table = $("#example").DataTable();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../json/stats.aspx?t=followed-companies",
dataType: "json",
success: function (data) {
for (i = 0; i < Object.keys(data).length; i++) {
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
url: "../json/stats.aspx?t=company-stats" + "&n=" + data[i]
}).done(function (dataSecondary) {
var stringtest = "<tr><td>" + dataSecondary.Stats1 + "</td>" +
"<td>" + dataSecondary.Stats2 + "</td>" +
"<td>" + dataSecondary.Stats3 + "</td>" +
"<td>" + '<button type="button" id="delete" class="btn btn-danger btn-xs dt-delete">' + "Delete" + "</td></tr>";
table.row.add($(stringtest)).draw();
});
}
},
error: function (xhr) {
console.log('error', xhr);
}
});
I do not have much experience in programming, but I do know that this takes ages to load and so has a very poor performance.
Main question is, can I use the table.draw(); after I have added the rows in that loop? I guess that could save some time. I tried to draw the table after the loop is finished but the table said that there is no data to show.
Second question, is this bad practise (mainly those nested Ajax calls with loops and SQL queries), and should I try to unify as many SQL queries as possible?