Mike Sav
Mike Sav

Reputation: 15321

Set value of a scoped variable in callback / closure

I have a very large JS script with many functions, callbacks and so on... one of my first actions is to obtain a value from an Ajax call. This value I then set to a global variable defined at the start of my script so I can reference the value again and again... the value with determine the user language for instance.

// define my global var at the top of my script..
var globalOpCo = "";

// I then try to give this a value in the next function I call...
$.ajax({
        url:"getURL",
        type:"POST",
        dataType:"json",
        success:function(data){
            if(data === null){
            // do something...  
            }else{
            // set the current language...
                globalOpCo = data.Opco.toLowerCase();
                console.log(globalOpCo); // this is the value I want it to be from data.Opco.toLowerCase() 
                // now do something.... 
            }
        },
        error:function(xhr, ajaxOptions, thrownError){
            console.log(xhr.status);
            console.log(xhr.statusText);
            console.log(thrownError);
        }
    });

Now later in my script I wish to pass the globalOpCo to another function like so...

 $("#aButton").on("click", function(){
        anotherFunction(globalOpCo); // I want to pass the globalOpCo as an arguement but its value isn't get updated above?
    });

however the value of globalOpCo is an empty string! The #aButton cannot be clicked before or until the ajax call above is run. Can someone help?

Upvotes: 1

Views: 118

Answers (3)

Keen
Keen

Reputation: 976

Global variables are just properties on the global object, which is window in browsers. You can avoid scoping issues by explicitly using window.globalOpCo.

Upvotes: 0

Mike Sav
Mike Sav

Reputation: 15321

Okay, I may have worked this out! It is scope, the variable is defined within $("document").ready(function(){}) whilst the function that is calling it is outside $("document").ready(function(){})

Upvotes: 0

Disable your button by default, add your onclick in your success function, after you define globalOpCo, and enable it when you set the onclick. Bonus: now it doesn't need to be global anymore, since the code that needs it is right next to it. Which is good =)

Upvotes: 2

Related Questions