Say for example, in my HTML file I have the following table rows in a table, where {{ }} are just variables:
<tr id="{{ object.id }}">
<td class="name">{{ object.name }}</td>
</tr>
<tr id="{{ object.id }}">
<td class="name">{{ object.name }}</td>
</tr>
Then in my JavaScript file I have the following code:
var rows = document.getElementsByTagName("tr");
for (var r = 0; r < rows.length; r++){
var tr = rows[r];
var id = tr.id;
$.ajax({
url: "/some-link/" + id,
success: function(some_json){
some_json = JSON.parse(some_json);
var td = document.createElement("td");
td.innerHTML = some_json;
//Problem is the following tr is referring to the last tr in the for loop by the time the AJAX request is complete
tr.appendChild(td);
}
});
}
The result I get is:
<tr id="{{ object.id }}">
<td class="name">{{ object.name }}</td>
</tr>
<tr id="{{ object.id }}">
<td class="name">{{ object.name }}</td>
<td>SomeJSON from when rows was 0 in the for loop</td>
<td>SomeJSON from when rows was 1 in the for loop</td>
</tr>
However, my intended result was:
<tr id="{{ object.id }}">
<td class="name">{{ object.name }}</td>
<td>SomeJSON from when rows was 0 in the for loop</td>
</tr>
<tr id="{{ object.id }}">
<td class="name">{{ object.name }}</td>
<td>SomeJSON from when rows was 1 in the for loop</td>
</tr>
I know I can fix this by adding to the AJAX request async: false
but I want to keep it asynchronous.
Any help will be much appreciated.