mazleu mazleu - 2 months ago 20
Javascript Question

Global variable set in function doesn't work

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?

Answer

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