0

I am trying to access a variable that I'm setting within a function. I need to access it outside of the function. I tried to set the variable first outside the function and then alter it from within the function, but that doesn't seem to work. Here's my code:

location_var =""; //i've tried both location_var and var location_var here

$.getJSON('/v/js/round.js', function(data) {

    var location_var = "location.pathname.indexOf('/product-p/test-product.htm')"

        for(i=0; i<data.records.length-1; i++){     
            var location_var = location_var + " || location.pathname.indexOf('" + data.records[i].productcode + "')";
        }

});

console.log(location_var);

I just get an empty string when it's logged out. When I log it out from within the JSON function, I get the correct value. I'm basically just looping through a JSON file and printing out the values.

I also tried what the answer said here (How to store a global value (not necessarily a global variable) in jQuery?) but trying to access the variables as $.getJSON.location_var but that didn't work either.

Thanks for your help!

Community
  • 1
  • 1
MillerMedia
  • 3,276
  • 16
  • 64
  • 132
  • 1
    [Asynchronous Vs. Synchronous Execution, What does it really mean?](http://stackoverflow.com/questions/748175/asynchronous-vs-synchronous-execution-what-does-it-really-mean). – Joseph Silber Sep 10 '13 at 00:29

2 Answers2

3

There are two problems with your code.

First of all - the scope of location_var is the inner function. For example:

var foo = 1;
(function(){
    var foo = 2;
})();
alert(foo); // alerts '1'

The second var creates a new variable scoped to the function, whereas the alert statement is looking at the foo variable attached to the outer scope.

You could fix that by removing the inner var - but that's a messy solution that pollutes the global scope - and won't work because of another bug in your code:

The getJSON call is asyncronous - that is, the remote request is sent, then other code is executed, then when the response is received the callback function is executed. In other words, at the time you log the value, the response has not yet been received.

You need to make sure that any code that relies on the new value of location_var is called from the callback, for example:

$.getJSON('/v/js/round.js', function(data) {
   ...code...
   console.log(location_var);
});
Hamish
  • 20,986
  • 7
  • 48
  • 67
0

Try this:

$.getJSON('/v/js/round.js', function(data) {

    window.location_var = "location.pathname.indexOf('/product-p/test-product.htm')"

    for(i=0; i<data.records.length-1; i++){     
        location_var = location_var + " || location.pathname.indexOf('" + data.records[i].productcode + "')";
    }

    console.log(location_var);

});
pdoherty926
  • 9,856
  • 2
  • 32
  • 54