Bogdan
Bogdan

Reputation: 1911

How can I call a bunch of functions that contain ajax sequentially?

I'm working on a window that has a bunch of elements that can each be edited separately and at the same time. I use ajax to bring over the editting layout then ajax again to change it back to how it will be displayed to customers. The thing is, I want each of the "open for editing" elements to get saved when the user clicks the window-wide save button.

Now, some guy decided it'd be fun to use anchor tags around images instead of onclick functions on them so I have to use eval to call the functions.

here's the code i'm using for the window-wide save button.

var as = document.getElementsByClassName('link_salvare');
alert(as.length);
for(var i = 0; i < as.length; i++) {
    alert(i);
    eval(as[i].href);
}
alert('finished');

the alerts are just there to see where it's going wrong and it turns out the for structure just stops after the first iteration (i=0). I get as.length as 2 (when I have 2 "editing" elements) but then I only get i=0 then 'finished'.

I tried with both asynchronous and non-asynchronous ajax calls and using asynchronous calls I get the above result while using the synchrronous calls I just get the alert and none of the elements are saved.

I could arrange so that only one element is ever edited at a time but that would have to wait until after the weekend to get clearance to change the individual save functions.

While this particular problem hasn't been fixed, I work around it by

a) changing from <a href="javascript:function"><img> to <img onclick="function"> in order to avoid using eval;

b) changing the design of the window so that only one element can be edited at any time.

I still have no idea why the 'for' loop only went trough one interation but I don't have time to investigate right now, best I can do is hope it doesn't bite me in the ass later;

Upvotes: 1

Views: 75

Answers (1)

rlemon
rlemon

Reputation: 17667

To touch on the eval().... and with that said I don't see any other issues.. you talk about ajax (XmlHttpRequest) yet you have provided no errors or code associated with it.

HTML

<a href="javascript:foo()" class="foobar">yoyo</a>
<a href="javascript:bar()" class="foobar">yoyo</a>​

Javascript

var elements = document.getElementsByClassName('foobar');

function foo() {
    alert('foo');
}

function bar() {
    alert('bar');
}

[].forEach.call(elements, function(element) {
    var func = element.href.split(':')[1],
        func_name = func.substring(0, func.lastIndexOf('('));
    window[func_name].call();
});​

I do highly suggest you alter the HTML source and not hack a solution like this. http://jsfiddle.net/rlemon/4vgPn/2/

Upvotes: 1

Related Questions