0
var InfoURL

$.get("https://ipinfo.io", function(response) {
    if(response.ip.indexOf(':') > -1) {
        InfoURL = 'google.com';
    } else {
        InfoURL = 'google.ch';  
    } 
    alert(InfoURL);
}, "jsonp");

alert (InfoURL);

So why is the second alert an empty variable? What must I change so that the variable is global?

Ryan
  • 14,392
  • 8
  • 62
  • 102
mazleu
  • 13
  • 9

1 Answers1

0

This is because the $.get function is asynchronous, You need to either use promises, or wrap the function into your own function that takes a callback like this:

function myGet(callback) {
    $.get("https://ipinfo.io", function(response) {
        if(response.ip.indexOf(':') > -1){
            callback('google.com');
        } else {
            callback ('google.ch');  
        } 
    }, "jsonp")
 }

Usage:

myGet(function(data) {
    alert(data);
});
Ryan
  • 14,392
  • 8
  • 62
  • 102
  • So if I want it synchronous which function would it be? – mazleu Sep 29 '16 at 23:06
  • 2
    @mazleu - You don't want it synchronous. That blocks the main thread and the browser may offer the user the option to kill your script. Arrange for the alert to be shown as part of the response processing. – Ted Hopp Sep 29 '16 at 23:08
  • Your example doesn't work. It says url not defined. – mazleu Sep 29 '16 at 23:14