12
    function genTask(elem){
    elem.each(function(){
        $this=$(this).parent('.cntTasks');
        var pattern=/taskId-(.*)$/
        var idTask=$this.attr('id').match(pattern);
        var data='id_task='+idTask[1];
        if(typeof jsVar2 !='undefined') data+=jsVar2;
        $.ajax({
             type: "POST",
             url: domain+"/view_tasks/gen_tasks/",
             dataType: 'html',
             data: data,
             success: function(dt){
                $this.find('.contChildTasks').html(dt);
                childs=$this.children('.taskDesc').find('.has_child');
                if(childs.length!=0)
                    genTask(childs);
                }
             }
        });
        $this.find('.taskDesc').show();

    });
}

if(typeof jsVar2 !='undefined') genTask($('.cntTasks .has_child'));


});    

how is possible to make $.each to wait until action $.ajax will be finished , and then continue loop , i cannot get $this var , because it has the last value , sorry for my English , THANK YOU !!!!

Samich
  • 29,157
  • 6
  • 68
  • 77
mIRU
  • 617
  • 3
  • 14
  • 32
  • Maybe you could set the `async` attribute of $.ajax to `false`? See: http://api.jquery.com/jQuery.ajax/ – Armin Dec 28 '11 at 15:01

4 Answers4

23

Option 1: Switch to next element in your array in the success handler.

Option 2: Make ajax requests synchronously:

  • global:

     $.ajaxSetup({ async: false });
    
  • or directly in the request:

     $.ajax({
         async: false,
         type: "POST",
         url: domain+"/view_tasks/gen_tasks/",
         dataType: 'html',
         data: data,
         success: function(dt){
            $this.find('.contChildTasks').html(dt);
            childs = $this.children('.taskDesc').find('.has_child');
            if(childs.length != 0) {
                genTask(childs);
            }
         }
    });
    
larrykkk
  • 459
  • 8
  • 10
Samich
  • 29,157
  • 6
  • 68
  • 77
0

try putting ajaxsetup({async:false}); before your each loop then after the loop reset it back to true so your future ajax request can still be async

sauhardnc
  • 1,961
  • 2
  • 6
  • 16
Laguna
  • 3,706
  • 5
  • 27
  • 42
0

Set async to false on the $.ajax call.

Tom van der Woerdt
  • 29,532
  • 7
  • 72
  • 105
0

In your $.ajax call add async: false and it will send a blocking request.

ridecar2
  • 1,968
  • 16
  • 34