I have an ul
with 9 li
elements. I want to load some information to these li
elements through ajax in asynch mode.
It's so simple, isn't it?
I just created a for(i = 1; i<=9; i++)
loop, and called the $.post
.
Fail: i
will be always 10, because the for loop running more faster, then the $.post
. So let's search the $.post in loop
on net.
I found three solutions. Two are here, and one is here.
All of it has the same effect: does not works asynchronously. Every time it load the first, then second, then third etc... Sometimes the order is changing, but every request wait while the previous finish.
I am using WIN 10 64bit, Apache 2.4 64 bit, php 5.6 64bit. Already tried on debian box, effect is the same.
In my php file, there is a sleep(1)
and an echo 'a'
.
My first attempt:
$('.chartContainer').each(function(index,obj) {
var cnt = index + 1;
$.post(getBaseUrl() + 'ajax.php', {dateTime: $('#chart_' + cnt).data('time'), action: 'getChartByDateTime'}, function (reponse) {
$(obj).html(reponse);
});
});
My second attempt:
for (var i = 1; i <= 9; i++) {
(function (i) {
var $obj = $('#chart_' + i);
$.post(getBaseUrl() + 'ajax.php', {dateTime: $('#chart_' + i).data('time'), action: 'getChartByDateTime'}, function (reponse) {
$($obj).html(reponse);
});
})(i);
}
My third attempt:
function loadResponse(i) {
var $obj = $('#chart_' + i);
$.post(getBaseUrl() + 'ajax.php', {dateTime: $('#chart_' + i).data('time'), action: 'getChartByDateTime'}, function (reponse) {
$($obj).html(reponse);
});
}
$(function () {
for (i = 1; i<=9; i++) {
loadResponse(i);
}
});
Expected result:
Every 9 li
loaded in 1 second in the same time.
Can somebody lead me to the right solution?
EDIT
Maybe I was not clear. In the production, the script will run for approx. 3 seconds. If I send one request to get all the data back, then it will take 9*3 = 27 seconds while the response arrives. This is why I want to send 9 request, and get back all the data in 3 seconds. I think this is why we use threads.
What I want is to get all the data for all li
in the "same" time. Not one by one, or get all in one request.
EDIT 2
Ok guys, shame on me, I think I mislead all of you. There is a session start in my php script.
If I remove everything, and then just echo something and die after sleep. In this case 5 request is responding in 1 sec, other 4 is later. But I think that is a new thred.