0

I am having a problem setting some global variables to use outside of the script that I am writing. I believe that I am setting them correctly but they don't seem to be cooperating. My console output is always an empty string, where as they are supposed to be defined inside the primary calling function of the demo web page. All of the other data seems to be working fine, if I print it out without setting it to a variable then it works fine. However I need the variables so that I can call them outside of this script. Any ideas?

var latitude = "", longitude = "";


$(document).ready(function() {
  $.ajax({
        dataType: "json",
        url:"http://api.geonames.org/searchJSON?q=Atlanta&maxRows=10&username=Demo"
}).then(function(data){
        console.log(data);
        latitude = data.geonames[0].lat; <---Variables are supposed to be set here
        longitude = data.geonames[0].lng; <----Variables are supposed to be set here
        $('.map-Latitude').append(data.geonames[0].lat); <----Works well
        $('.map-Longitude').append(data.geonames[0].lng); <----Works Well
    });
});


console.log("Latitude is: " + latitude); <---- prints out an empty string
console.log("Longitude is: " + longitude); <---- prints out an empty string

I cant seem to get this to work, I feel like I am setting the variables properly but they don't seem to be working well. Thanks!

1 Answers1

1

Your $.ajax() call is asynchronous. The results of the call are not available until the HTTP response is received by the browser.

Put your console.log() calls inside the .then() function.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Okay I see what you are saying, my question then is how do I make use of this information outside of this function, how can I set the necessary information to variables for use later –  Nov 29 '14 at 23:28
  • 1
    @RichardDavy you don't. In an asynchronous environment, it's all about those callbacks. From the callback you can invoke any sort of behavior you want. – Pointy Nov 29 '14 at 23:29
  • Gotchya, Thank you, I figured out my issue and now have it working. I understand what you were talking about now, so I have built my methods accordingly, thank you. –  Nov 29 '14 at 23:40