0

I have the following jQuery:

$.getJSON('http://www.geoplugin.net/extras/postalcode.gp?format=json', function(data) {
    console.log(data.geoplugin_postCode);
    var zipCode = data.geoplugin_postCode;
    alert(zipCode);
});
alert(zipCode);

for some reason when I do that alert below,

alert(zipCode)

I get undefined. I need the zipCode to be accessible outside of jQuery. I get the alert for zipCode inside the getJSON.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
unixmiah
  • 3,081
  • 1
  • 12
  • 26
  • 1
    that's not how JS works. It's all async and event driven. Whatever is inside the `function(data)` body will get executed after your `alert` outside of the function – Poul Kruijt Oct 08 '20 at 17:06
  • 1
    This is because the code you posted is async. Read up on async/await and callback functions. – wootscootinboogie Oct 08 '20 at 17:06
  • See the answer to this SO question for a good explainer on async JS : https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Vanquished Wombat Oct 08 '20 at 17:10
  • 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) – freedomn-m Oct 08 '20 at 18:53
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Guy Incognito Oct 09 '20 at 11:35

0 Answers0