-1
$('#liveUpdate').click(


        $.getJSON("http://freegeoip.net/json/", function(data) {
            var country = data.country_name;
            var ip = data.ip;
        });

        alert(country);

    });

I wanted to use country outside getJSON but not the correct result. Tried to define variable top of the click function but not resolved my problem.

How can I fix it?

Jonathan D.
  • 115
  • 1
  • 13
  • 1
    you can try `$('#liveUpdate').click(function() { var country = null; $.getJSON("http://freegeoip.net/json/", function(data) { country = data.country_name; var ip = data.ip; }); alert(country); });` – Sushil Sep 01 '15 at 21:58
  • 1
    @Sushil: That won't work. AJAX is *asynchronous*. – gen_Eric Sep 01 '15 at 21:59
  • @Bergi - Heh, you got in right as I clicked close with that same target :) – Travis J Sep 01 '15 at 22:00
  • you're right @RocketHazmat he can just use `$.ajax` with `async: false` – Sushil Sep 01 '15 at 22:00
  • 1
    @Sushil: I would *not* suggest that, it's a bad practice. It locks up the browser and doesn't teach you the correct way to use AJAX. – gen_Eric Sep 01 '15 at 22:03
  • yeah that's true but if its not a heavy function, why not use it or he can go with @Ammar's approach – Sushil Sep 01 '15 at 22:07

1 Answers1

-1

Change your approach to work with the asynchronous nature of ajax.

Say you wanted to use country in a function

function someFunction(country){
    //country used here
}

Then call it within the success callback of the ajax

$('#liveUpdate').click(function(){
        $.getJSON("http://freegeoip.net/json/", function(data) {
            country = data.country_name;
            var ip = data.ip;
            someFunction(country);
        });

    });
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53