Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra parameter for jQuery's ajax success function

I'm fetching an XML file using this code:

function getMaps(){

    toLoad = loadMaps.length;

    for (var i = 0; i < loadMaps.length; i++){
        $.ajax({
          type: "GET",
          url: loadMaps[i],
          dataType: "xml",
          success: processMap
        });
    }
}

Which works fine, but I want to give processMap another parameter (namely loadMaps[i], the name under which to store the loaded xml)

I can't figure out how to do this without resorting to global variables, which is not what I want.

like image 617
skerit Avatar asked Jul 14 '10 09:07

skerit


3 Answers

The jQuery success callback has three parameters, which cannot be changed or expanded. So you need to call your function within an anonymous function which closes over.

for (var i = 0; i < loadMaps.length; i++){
    $.ajax({
      type: "GET",
      url: loadMaps[i],
      dataType: "xml",
      success: function(xhr, textStatus, error){
           processMap(loadMaps[i]);
      }
    });
}
like image 189
jAndy Avatar answered Nov 05 '22 02:11

jAndy


function getMaps(){
    toLoad = loadMaps.length;

    for (var i = 0; i < loadMaps.length; i++){
        $.ajax({
          type: "GET",
          url: loadMaps[i],
          dataType: "xml",
          success: function() {
              // do anything
              processMap(x,y,z,'foo');
          }
        });
    }
}
like image 1
Māris Kiseļovs Avatar answered Nov 05 '22 03:11

Māris Kiseļovs


The problem of accepted issue that "i" will be always with the last value in the loop, at least the Success event happens faster than next iteration of a loop, which is almost never happens.

Here is how it worked in my case:

function getMaps(){

    toLoad = loadMaps.length;

    for (var i = 0; i < loadMaps.length; i++){
        $.ajax({
          type: "GET",
          url: loadMaps[i],
          dataType: "xml",
          success: (function(loadMap){
              return function processMap(response){
                // code of processMap function ...
                alert(loadMap);
              }
          })(loadMaps[i])
        });
    }
}

Here is the original answer of similar question: how to pass multiple arguments to onSuccess function in Prototype?

like image 1
Kostanos Avatar answered Nov 05 '22 02:11

Kostanos