Why when using each loop, the returned values are not in the same order?
I have a code in php
$selectedYear = 2018;
$months = array (
0 => 'January',
1 => 'February',
...
11 => 'December'
);
Now, foreach $months
i want to create new row (<tr>
) with different value etc. I'm using AJAX for it like:
var selectedYear = <?= json_encode( $selectedYear ) ?>;
var month= <?= json_encode( $months); ?>;
$(month).each(function(k)
{
$.ajax({
type : 'POST',
url : 'scripts/ajax-monthTr.php',
data : {month: k, selectedYear: selectedYear},
beforeSend: function()
{
$('.preloader').css('display', 'block');
},
success : function(data)
{
$('#newTr').append(data);
$('.preloader').css('display', 'none');
}
}); // end ajax
});
And i've got result not in order like:
<table>
<tr id="0">January</tr>
<tr id="3">April</tr>
<tr id="2">March</tr>
<tr id="5">July</tr>
<tr id="1">"February"</tr>
...
</table>
Any solution for it? Have i missed something?
I tried
$(month).each(function(k)
or
for(var i = 0; i < month.lenght; i++)
That's because result of each ajax call is returning data at different interval. You can:
1) Either append the data before calling ajax function.
2) or, sort the tr elements based on id attribute after appending new row in every ajax function
var items = $('#newTr tr');
items.sort(function(a, b){
return $(a).attr('id') - $(b).attr('id');
});
items.appendTo('#newTr');
You're doing one request to fetch data from a month i without waiting the response from request to fetch the month i-1. Say you make a request to fetch data from month 1, then you don't wait for the response to this request, and also you make a request for month 2, maybe the response for month 2 can arrive before the response for month 1. Also take a look at this technique: https://en.wikipedia.org/wiki/HTTP_pipelining
Looks like you are expecting synchronous behavior from AJAX calls. Your code is using a callback, so this function
success : function(data)
{
$('#newTr').append(data);
$('.preloader').css('display', 'none');
}
will be triggered after each POST. The arrival order of those POST calls do not depend on you. You should reconsider doing the loop after all the network calls have been completed.