0

I'm trying to figure out why this isn't working. I thought I understood scope...

var admin_data = false;
function getPlayerAdmin(){
    var formData = {
        'player_id' : $('#post-v').attr('data-val')
    };
    $.ajax({
        type: 'post',
        url: '/popins/player/controls',
        data : formData,
        dataType : 'json',
        success: function(admin_data) {
            if(admin_data.controls.is_admin == true){
                admin_data = true;
            }else{
                admin_data = false;
            }
        }
    });
}
alert(admin_data);

So basically admin_data is being set to true, however it doesn't change it when I alert it after. How do I pass this back down?

Thanks!

So far I have this now:

var admin_data = false;

adminData(function(admin_data) {
    if(admin_data_vals.controls.is_admin == true){
        admin_data = true;
    }else{
        admin_data = false;
    }
});

function getPlayerAdmin(adminData){
    var formData = {
        'player_id' : $('#post-v').attr('data-val')
    };
    $.ajax({
        type: 'post',
        url: '/popins/player/controls',
        data : formData,
        dataType : 'json',
        success: adminData
        },
        error : function(jqXHR, textStatus, errorThrown){
            console.log(jqXHR);
        }
    });
}
alert(admin_data);

3rd attempt:

var admin_data = false;
function getPlayerAdmin(admin_data){
    var formData = {
        'player_id' : $('#post-v').attr('data-val')
    };
    $.ajax({
        type: 'post',
        url: '/popins/player/controls',
        data : formData,
        dataType : 'json',
        success: function(admin_data_vals, admin_data) {
            if(admin_data_vals.controls.is_admin == true){
                admin_data = true;
            }else{
                admin_data = false;
            }
        },
        error : function(jqXHR, textStatus, errorThrown){
            console.log(jqXHR);
        }
    });
}
getPlayerAdmin();
alert(admin_data);

1 Answers1

1

You can do many things here to resolve this with things like promises, deferred objects, etc., but you could simply just do your logic in the success/error callbacks if there isn't much complexity to what you need to do with the response.

success: function(adminData) { // Should probably change the parameter name
                               // to not be the same as the variable you are setting
  if (adminData.controls.is_admin == true) {
    admin_data = true;
    alert(admin_data);
  } else {
    admin_data = false;
    alert(admin_data);
  }
}
JB06
  • 1,881
  • 14
  • 28