ey dee ey em
ey dee ey em

Reputation: 8623

Variable passed from one function to another become undefined after .post with jQuery

I have a function successfully pass data_user_id with a value of 2 into the function getOptionsList(fieldname_validation,data_user_id) But then, I think somehow the .post statment's async nature took the value out so when I do a .post in the getOptionsList function, then the data_user_id will be undefined in function it passed next. Like this:

function getOptionsList(fieldname_validation,data_user_id){ 
        $.post('Controller.php',
        {
            action: 'get_options_list',
            user: userJson
        },
        function(data, textStatus, fieldname_validation,data_user_id) {
            data_user_id=data_user_id;
            showOptionsList(data, fieldname_validation,data_user_id);
            $('#indicator').hide();
        }, 
        "json"      
    );  
}

function showOptionsList(jsonData, fieldname_validation,data_user_id){

    alert('showOptionsList ran!');
    alert(data_user_id);//Here the same variable will alert as undefined.
}

How can I fix this issue?

Upvotes: 0

Views: 1050

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149060

You've declared data_user_id as a parameter to your inner function, so it's distinct from the parameter of the outer method. Since the $.post method will only provide 3 parameters to the callback, the fourth parameter will always be undefined (the third parameter will be a jqXhr object, which I don't believe is what you expect).

The solution is to remove this parameter (and probably fieldname_validation as well):

function getOptionsList(fieldname_validation,data_user_id){ 
        $.post('Controller.php',
        {
            action: 'get_options_list',
            user: userJson
        },
        function(data, textStatus) {
            showOptionsList(data, fieldname_validation, data_user_id);
            $('#indicator').hide();
        }, 
        "json"      
    );  
}

Upvotes: 2

Related Questions