The reason it doesn't work out for you is that the call to getJSON
is an asynchronous call. In sense it means that it is ripped out of the current flow and executed somewhere independently. Take a look at the comments I have added to your code below:
var voted;
//getJSON is executed right away - async
$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){
//This callback function executes when the remote request responds. The timeframe is variable.
voted = data.host;
console.log(voted);
});
//Gets executed right away - doesn't wait for getJSON to get the remote response.
//voted is probably still undefined.
console.log(voted);
What you need to to is add a function that continues your flow, as shown below:
$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){
voted(data.host);
});
function voted(ip) {
ip_voted = ip_array.indexOf(ip);
if (ip_voted > -1) {
window.location.href = "results";
}
verify(ip);
}
function verify(ip) {
if (choice && ip == '123123123') {
}
}
If you really need to use the data in a global variable, you could "wait" for the response - however I strongly advise against doing this:
var host, value;
var responseArrived = false;
$.getJSON("http://smart-ip.net/geoip-json?callback=?", function(data){
host = data.host;
value = data.value;
responseArrived = true;
});
while( !responseArrived ) {
//NOT A GOOD IDEA!
//Will continue to loop until the callback of getJSON is called.
//NOT A GOOD IDEA!
}
console.log(host);
console.log(value);