JohnWalker891212
JohnWalker891212

Reputation: 5

Global Variable - AJAX jQuery

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();
});

Upvotes: 0

Views: 586

Answers (1)

Yang
Yang

Reputation: 8701

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

Upvotes: 1

Related Questions