0

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?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
BootDev
  • 146
  • 2
  • 9
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – evolutionxbox Jan 27 '21 at 11:24
  • The `console.log` and `getCurrentPosition` will likely be called before `currentCountry`. Don't use global variables to return data from an async function. Check out the linked question for more information. – evolutionxbox Jan 27 '21 at 11:26
  • As above, here's what your code currently says: create a variable (not defined yet), start a request, use the variable, get the response back to set the variable. Add a bunch of (different) console.logs (eg 1st line, in success: last line) and see what order they appear. – freedomn-m Jan 27 '21 at 11:31
  • 1
    "Don't use global variables to return data from an async function". Ah of course! I'm doing that all through my code. And all there errors seems like this would be the reason. Thank you for the link! :) – BootDev Jan 27 '21 at 11:33
  • Put even more simply, you're trying to eat a pizza before it's been delivered :) Check the duplicate questions for more information. – Rory McCrossan Jan 27 '21 at 11:33

0 Answers0