I'm trying to figure out the cause of several errors and it seems it has to do with the scope of my variables. I've stripped down my code to try and isolate part of the problem. I'm using PHP and jQuery to access the OpenCage api (that works fine) and get a user's location.
I can't seem to get a grasp why my global variable is not working.
let currentCountry;
//User's Location info
function successCallback(position) {
$.ajax({
url: "assets/php/openCage.php",
type: 'GET',
dataType: 'json',
data: {
lat: position.coords.latitude,
lng: position.coords.longitude,
},
success: function(result) {
console.log('openCage User Location', result);
currentLat = result.data[0].geometry.lat;
currentLng = result.data[0].geometry.lng;
currentCountry = result.data[0].components["ISO_3166-1_alpha-2"];
console.log("current country inside function", currentCountry);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
const errorCallback = (error) => {
console.error(error);
}
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
console.log("current country outside function", currentCountry);
When I console.log(currentCountry)
in the AJAX call I get the correct result. But of course when I do it outside the function I get undefined
even though I declared the empty variable outside the AJAX call.
How can I make the currentCountry
variable global so that I can use it in other functions/API calls?