views:

28

answers:

2

I have an array that stores a few urls of XML files that need to be downloaded. On success, these files need to be processed. But that is where it goes wrong. The problem is quite apparent:

for (var i = 0; i < loadMaps.length; i++){

    var currentMap = loadMaps[i];

    $.ajax({
      type: "GET",
      url: currentMap,
      dataType: "xml",
      success: function(xml, textStatus, error){
        processMap(xml, currentMap)
      }
    });
}

As you can see, it loops through the array and downloads the correct map. That's great. But by the time the file has been downloaded, the other file is being downloaded, too! And as such the "currentMap" variable has changed.

So this would cause both files to be processed under the same name. Which is wrong.

What's the best way of fixing this?

A: 

I think i should work like this:

for (var i = 0; i < loadMaps.length; i++){
    $.ajax({
      type: "GET",
      url: loadMaps[i],
      dataType: "xml",
      success: function(xml, textStatus, error){
        processMap(xml, loadMaps[i])
      }
    });
}
Māris Kiseļovs
It probably won't work, because `i` changes as well.
Pekka
Indeed. I first had it like that, but even with only 1 item in the array `i` changed.
skerit
+1  A: 

This is because per default JQuery sets asynchronous to true. If you require everything in a specific order you either need to set it to false or store everything in a temporary object which is processed in a specific order when all GET is completed.

Anders
Indeed, that did it. Once I added `async: false,` to the jquery command it worked. I still can't dump the `var currentMap = loadMaps[i];` though, but that's OK.
skerit
What you are saying is variable currentMap is not assinged value of array loadMaps[position]?
Anders