.ajax are asynchronous. The callback functions that you provide them are called some time later in your program (after the browser’s finished reading your code).
If you walk through your original code, first the code checks if the browser supports geolocation. If it does, it will get the current position. But it won’t return them immediately, so you provide a callback function that will be called back later, which describes what to do with the position data once that data is available.
After you’ve registered a geolocation callback function, your code will try to request some weather data via
.ajax(). It will try to get some data from the URL that you provided, but at this point, the
longitude variables are still empty (because the code that will provide them is waiting to be called back), and you’ll get an error.
By putting the
.ajax() call inside the geolocation’s callback function, a weather request will not be made until the geolocation data is available.