Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access ajax call's parameters in the success function?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 ) 
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading