0

I'm trying to set the global variable countryCode. But the value is always null. What can I do? I tried many ways. PLS HELP!

function GetGeolocation(){

  $.getJSON("http://ip-api.com/json/?callback=?",function(data){
  $.each(data, function(k, v) {
    table_body += "<tr><td>" + k + ": " + "</td><td><b>" + v + "</b></td></tr>";

      if (k == "countryCode")
      {
          SetGeolocation(v);
      }
    })             
  }); 
}

function SetGeolocation(value){

  countryCode = value;
  console.log(countryCode); //Value
}

function Result(){
  console.log(countyCode); //Null
}

$(document).ready(function(){
  GetGeolocation();
  Result();
});
8
  • It doesn't look like you've made countryCode a global variable. You could try replacing countryCode with window.countryCode whenever it is used to make it a global variable Commented Mar 7, 2015 at 23:26
  • 1
    Try adding var countryCode; above the first function to set it as a global. Commented Mar 7, 2015 at 23:27
  • 1
    @user1063998 countryCode is a global variable. If you don't declare a variable with var in js - it is global. The fact it's value is Null but not undefined proves this. Commented Mar 7, 2015 at 23:28
  • Where is function Result() being called? Is it after the other functions have run? Commented Mar 7, 2015 at 23:30
  • 1
    Have you waited for the ajax call to finish before calling Result()? It is a asynchronous you know... Commented Mar 7, 2015 at 23:38

1 Answer 1

1

In JavaScript, a variable which has been declared without var keyword inside a function becomes global only after function's call.

Consider this:

function foo(){
    bar = 123;
}

// Reference error - bar is undefined
console.log(bar);

Now before testing bar variable, let's call the foo function.

function foo(){
    bar = 123;
}

foo();

// 123
console.log(bar);

You got it? Right? Good. As for your code, the error is pretty obvious countryCode is undefined just because you didn't call SetGeolocation() before. To make it work as you expect you need somehow call SetGeolocation() before you call Result().

But don't do this seriously. Global variables is well-known what not to do thing. Consider passing a variable as a dependency instead

Sign up to request clarification or add additional context in comments.

1 Comment

i tried to call the function Result() in SetGeolocation() and it worked! thx!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.