0

I'm writing for loop to show created links and using this loop:

for (var x = 0; x < data.succeeded.length; x++) {

    $.post("{{URL::action('make')}}", {url: "{{URL::route('home')}}/uploads/" + data.succeeded[x].file, name: data.succeeded[x].name}, function(url) {

        anchor = document.createElement('a');
        anchor.href = url;
        anchor.target = '_blank';
        anchor.innerHTML = x + ' ' + data.succeeded[x].name + '<br><small>(' + url + ')</small>';

        succeeded.appendChild(anchor);
    });
}

but in $.post function url name (data.succeeded[x].name) allways stay the same only url updates. But if I use console.log on 2nd line (after for() {) url name changing as it should.

What did i wrong?

Mivaweb
  • 5,580
  • 3
  • 27
  • 53
Mik
  • 151
  • 3
  • 4
  • 14
  • 1
    Can you setup a jsfiddle that replicates the issue? there is othing obvious in this portion of your code. – Jay Blanchard May 23 '14 at 12:46
  • Well it's a bit hard to me, cuz i never used this one :/ but if u wish u can visit a website. [WebSite here](http://revix.no-ip.biz/laravel/public/) just try to upload few files and all time show only first file name, but links updating normally. – Mik May 23 '14 at 12:51
  • 1
    Please, refer to this : http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Karl-André Gagnon May 23 '14 at 12:52

1 Answers1

2

Please dont execuse async calls like the above within a loop, there are way too many points of failure. If the server times out, you have many requests pooling up and doing nothing as well as the order of return is not guaranteed. It's better to call the next AJAX call in the callback of the one that just completed, then you have everything in order and it guarantees that one request won't happen until the other completes:

function makeAjaxCall(position) {
    $.post("{{URL::action('make')}}", {url: "{{URL::route('home')}}/uploads/" + data.succeeded[position].file, name: data.succeeded[position].name}, function(url) {

        anchor = document.createElement('a');
        anchor.href = url;
        anchor.target = '_blank';
        anchor.innerHTML = position + ' ' + data.succeeded[position].name + '<br><small>(' + url + ')</small>';

        succeeded.appendChild(anchor);
        if (position < data.succeeded.length) makeAjaxCall(++position);
    });
}

makeAjaxCall(0);
tymeJV
  • 103,943
  • 14
  • 161
  • 157