mal200
mal200

Reputation: 389

JQuery - Sending extra parameters to callback function

When using the $.ajax() function for sending a request for information from server-side scripting, can you pass parameters to the callback function?

Example:

var params = ['param1', 'param2', 'param3']; 
for (var i = 0; i < params.length; i++) {
    $.ajax({
        url: url,
        dataType: "json",
        success: function(json, textStatus, jqXHR){
            console.log(params[i]);             
        }
    });
}

but it doesnt work. do you have an idea?

Upvotes: 0

Views: 329

Answers (2)

Sam R
Sam R

Reputation: 702

Both params and i exist in the global namespace, so each success will get you the last value of i, assuming the AJAX call takes longer than the for loop (boy, it better).

Wrap your AJAX call in a function and pass the parameter into the function. You can then call it directly from inside success.

Upvotes: 2

Anthony Hatzopoulos
Anthony Hatzopoulos

Reputation: 10537

You have to pass it to your url using the data option then return it in the response, thus having it in the async success callback.

By the way you should probably wrap the entire ajax bit in a function outside the for loop and call it from within the loop. Like this

var params = ['param1', 'param2', 'param3']; 

function do_stuff(param){
    $.ajax({
        url: url,
        dataType: "json",
        data: {
            'param' : param
        },
        success: function(json, textStatus, jqXHR){
            console.log(json.param);    
        }
    });
}

for (var i = 0; i < params.length; i++) {
  do_stuff(params[i]);
}

Upvotes: 1

Related Questions