Shiva Acharjee Shiva Acharjee - 1 year ago 107
Ajax Question

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',
/*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++)

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 ive 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.
Any help is appreciated asap.
Also can this be used somehow and if then how?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download