0

I am trying to read a variable outside of a function. I am doing a country detection using an API and looking up a JSON feed. I get the result fine, but I want to be able to use this result outside of the function and I have tried my best, but can't understand how to fix this. My code attempt so far.

var country; // defining country outside of function.

jQuery.getJSON('https://api.wipmania.com/jsonp?callback=?', function (data) { 

    var country = data.address.country;
    console.log(country) // this returns correct result

}); // end location country check function

console.log(country) // This is reading undefined as is not picking up the new var = country resulted from above function.

How do I use the new resulted country variable outside of the function?

Thank You

PSL
  • 123,204
  • 21
  • 253
  • 243
Redwall
  • 1,010
  • 5
  • 30
  • 55
  • Remove the second 'var' (inside the function). – gbs Nov 26 '13 at 15:58
  • 1
    The important thing to note is that getJSON is a **deferred function** not any other function. It does not run synchronously like your expecting it to. – Liam Nov 26 '13 at 15:59
  • @PSL thanks, I could not find that answer today at all. Must of been searching for wrong keywords..Damm -1 for not seeing that, anyway..cheers for help everyone – Redwall Nov 26 '13 at 16:13

2 Answers2

4

getJSON works in an asynchronous way.

The last console.log is called before the callback.

CD..
  • 72,281
  • 25
  • 154
  • 163
1

when you declare var country you are shadowing the global country. As CD.. pointed out getJSON is asynchronous so you will need to check if it has been set before using it

var country; // defining country outside of function.

jQuery.getJSON('https://api.wipmania.com/jsonp?callback=?', function (data) { 

   country = data.address.country;
   console.log(country) // this returns correct result

}); // end location country check function

console.log(country || "No country set yet, check back soon!");