0

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.

Community
  • 1
  • 1
vaso123
  • 12,347
  • 4
  • 34
  • 64
  • 1
    Why don't you send all 9 values to the php script, process them and return the proper results? – Alex Andrei Mar 17 '16 at 09:51
  • Like commented above, the way to go is to use only one request to send all relevant data to server only once – A. Wolff Mar 17 '16 at 09:57
  • Ok, but this is my problem. In the production, the script will run for approx. 3 seconds. If I send one request, 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. – vaso123 Mar 17 '16 at 09:59
  • I don't see any problems with your second attempt, apart from variable names =). It is here https://jsfiddle.net/a5pacfjg/ It executes 6 requests at a time because of browser limitation of simultaneous requests. – Alex Blex Mar 17 '16 at 10:17
  • session lock problem as @Arno mentioned. Sorry for disinformation. I never met with this before. Downvote me :) – vaso123 Mar 17 '16 at 10:19

4 Answers4

2

From the jQuery manual:

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

Are you sure the requests are not sent by your browser? It is possible your php script does not allow multiple sessions. Have you tried inspecting the ajax calls with firebug/chrome inspector?

Edit:

PHP writes its session data to a file by default. When a request is made to a PHP script that starts the session (session_start()), this session file is locked. What this means is that if your web page makes numerous requests to PHP scripts, for instance, for loading content via Ajax, each request could be locking the session and preventing the other requests from completing.

The other requests will hang on session_start() until the session file is unlocked. This is especially bad if one of your Ajax requests is relatively long-running.

Possible solutions:

  1. Do not use sessions when you don't need them
  2. Close your session after reading/writing the necessary information:

    session_write_close(); 
    
  3. Store your sessions in Redis/mySQL for example
Arno
  • 161
  • 10
  • This is a comment instead of answer. Anyway, all the ajax is in the network inspector immediatly when page loads. But executed after each other> http://vaso.hu/other/ajax/astroajax.jpg – vaso123 Mar 17 '16 at 09:54
  • This looks like the requests are waiting for the previous one to finish. Do you use a session_start() in the php script? – Arno Mar 17 '16 at 10:07
  • Yes, I do. How is it effects on the script? – vaso123 Mar 17 '16 at 10:09
  • The short version: PHP opens a file with session information and holds a lock on this file. As long as you dont terminate the session and the scripts is not finished other scripts with the same session ID will wait until this script is finished (the lock is released). I'll edit my answer with more info. – Arno Mar 17 '16 at 10:15
1
function loadResponse(i) {

    var $obj = $('#chart_' + i);
    $.post(getBaseUrl() + 'ajax.php', {dateTime: $('#chart_' + i).data('time'), action: 'getChartByDateTime'}, function (reponse) {
        $($obj).html(reponse);
        if(i<=9) loadResponse(++i);
    });
}
var i = 1;
$(function () {
    loadResponse(i);
});

Here loadResponse function is being called first time at the page load. Then it is being called recursively on the response of the POST request.

Aju John
  • 2,214
  • 1
  • 10
  • 27
  • Code only answers rarely provide much insight / explanation to OP, please explain what you have done / what your code does and why / how it works. – Epodax Mar 17 '16 at 09:49
  • Sure man..! first i called loadresponse function on the page load, and after getting the response of the post call i am again calling the function recursively. (for 9 times, as i am checking the condition). So the loadresponse will be called after getting the response of previous call...!! thats it.. – Aju John Mar 17 '16 at 09:51
  • Please edit it into your answer :) Comments are at risk of being overlooked / deleted. – Epodax Mar 17 '16 at 09:52
  • It not works for, me it just load 1. And anyway, I want to get back all the data in the same time for all `li` not on by one. – vaso123 Mar 17 '16 at 10:02
  • OKay..just checked your edit....So u can do one thing.. you can hide the li tags at starting and when the loop completes you can make it show – Aju John Mar 17 '16 at 10:10
0

You can try this.

for (var i = 1; i <= 9; i++) {
    var $obj = $('#chart_' + i);
    var time = $('#chart_' + i).data('time');
    (function ($obj, time) {
        $.post(getBaseUrl() + 'ajax.php', {dateTime: time, action: 'getChartByDateTime'}, function (reponse) {
            $obj.html(reponse);
        });
    })($obj, time);
}
rrk
  • 15,677
  • 4
  • 29
  • 45
0

Try sending all the data at once

var dateTime = [];
$('.chartContainer').each(function(index,obj) {
    var cnt = index + 1;
    dateTime.push({date:$('#chart_' + cnt).data('time'),el:'#chart_' + cnt});

});
 $.post(getBaseUrl() + 'ajax.php', {dateTime:dateTime , action: 'getChartByDateTime'}, function (reponse) {
       $.each(reponse,function(i,v){
          $(v.el).html(v.procesedData);
       });

    });

php :

$ajaxresponse =[];
foreach($_POST['dateTime'] as $datetime) {
   $data = $datetime['date'];//change this with your results
   $ajaxresponse[]= array('procesedData'=>$data,'id'=>$datetime['id'])
}

return json_encode($ajaxresponse);
madalinivascu
  • 32,064
  • 4
  • 39
  • 55