The problem here is that the code in the success
callback is only executed once you have received the AJAX response. So the order of execution is like this:
- The first half of the table (
<table>
to <tbody>
) is added to table_html
.
- The AJAX call is initiated.
- The second half of the table (
</tbody>
to </table>
) is added to table_html
.
- The content of
table_html
, without the middle part with the data that has not yet been added since the success
callback has not yet been executed, is appended to your modal.
- The
success
callback is executed once the AJAX call gets a response. It adds the middle parts of the table (all the <tr>
) to the end of the variable, but it makes no difference since the table has already been appended.
This post gives a good general explanation of the problem.
In your case, you can solve the problem like this:
//Append an empty table.
var table_html = '<table id="my_table">';
table_html += '<thead>'
table_html += '<th>No</th>'
table_html += '<th>Name</th>'
table_html += '</thead>'
table_html += '<tbody>'
//This row will show a loading message.
//It will be removed once the actual content has loaded.
table_html += '<tr><td colspan=2>Loading content...</td></tr>'
table_html += '</tbody>'
table_html += '</table>'
$("#myModal .modal-body").html(table_html);
//Do the AJAX call.
$.ajax({
url:'/reports/name-report',
type:'POST',
data: options,
success:function(result){
//This code will only run when you get the AJAX response.
//Create the inner part of the table.
var tr_html = "";
$.each(result.details, function(i,obj){
i = i + 1;
tr_html += '<tr>'
tr_html += '<td>'+i+'</td>'
tr_html += '<td>'+obj.name+'</td>'
tr_html += '</tr>'
})
//Append the inner part to the table.
//This will overwrite the tr with the loading message we added earlier.
$("#my_table tbody").html(tr_html);
}
});
Disclaimar: I have not tested this code.