Home > Back-end >  How to access ajax call's parameters in the success function?
How to access ajax call's parameters in the success function?

Time:01-03

I'm doing several ajax calls of the following type in a loop:

var param1Val = 'will be different in each loop';
var param2Val = 'will be different in each loop';

$.ajax({
    type: 'POST',
    url: someUrl,
    dataType: 'xml',
    data: {
        'param1': param1Val,
        'param2': param2Val
    },
    success: function(result){
        // how to access param1 and param2 here???
    }
});

and I need to access somehow the param1 and param2 in the success part. I can't use the global param1Val and param2Val variables, because they will have the value of the last loop until I get some response from the server.

CodePudding user response:

By creating a closure you can do this.

var successFunc = function(param1Val, param2val) {
     return function(result) {
       // Access param1Val and param2val here, also can access the api result 
     }
}
$.ajax({
    type: 'POST',
    url: someUrl,
    dataType: 'xml',
    data: {
        'param1': param1Val,
        'param2': param2Val
    },
    success: successFunc(param1Val, param2val ) 
});
  • Related