Search code examples
javascriptajaxasynchronousprototypejs

Get data asynchronously JavaScript within for loop


I have this function

function add_cnh(arr_clelem){

  var id=arr_clelem.getElementsByClassName("present")[0].id;
  var date=arr_clelem.getElementsByClassName("present")[0].getAttribute('date');
  var tt_entry= arr_clelem.getElementsByClassName("present")[0].getAttribute('tt_entry'); 


//new Ajax.Updater('register', '/some_url', { method: 'get' });

new Ajax.Request('/attendances/new',
{
    parameters:'id='+id+'&date='+date+'&timetable_entry='+tt_entry+'&subject_id='+subject_id,
    asynchronous:true,
    evalScripts:true,
    method:'get'
 /*onSuccess: function(transport) {
var response = transport.responseText || "no response text";
alert("Success! \n\n" + response);
}*/

}
)
var ret=modal_data;
  // $$('.MB_close').invoke('observe', 'click', _deinit);
return ret;

}

This function takes html-elements-object as an argument and basically render a modal-box and that modal box contain a form -elements which i need to store inside an array. The variable modal_data contains the elements which I require and its a global variable define in another file.

My problem is This is a very old project using many JavaScript frameworks and libraries which date back to 2006 the library responsible for opening the model box itself is deprecated as can be seen here

And somehow I don't want to get into server side so I am using a for loop something like this

for(var i=0; i<arr_of_elements.length, i++)
{
   my_arrvar[i]=add_cnh(arr_of_elements[i]);
}

Now with each itteration since I want the modal box to get closed and store the data within 'my_arrvar' which is somehow not possible as the call is asynchronous in nature and I've used closures and callbacks but no success. I don't want to use any sort of timer. So this is how it goes

Call the function and get data for each call and remove the modal box by id.

Also can this be used somehow and if then how?


Solution

  • You have to pass in ajax request asynchronous:false instead of true. Otherwise its not possible by another way.

    Other Way using jQuery

    The easiest way is to use the .ajaxStop() event handler:

    $(document).ajaxStop(function() { // place code to be executed on completion of last outstanding ajax call here });

    See jQuery Event handler