jQuery ajax returns promises, which you can use:
function getUserLocation() { return $.ajax('https://www.example.com/location.json'); // note the `return` } function getCurrentWeather(userLocation) { return $.ajax('https://www.example.com/weather' + userLocation + '.json'); } getUserLocation().then(getCurrentWeather).then(function(data) { // location data here });
Or, in more detail
getUserLocation().then(function (user) { return getCurrentWeather(user); }).then(function(data) {
The best solution would be to make it one call, not two calls, as many AJAX calls slow down your application, especially on mobile devices with limited bandwidth.
Here is a callback based approach that is likely to be inferior to the promise (e.g. with error handling), but I feel like we should show it for completeness. You can read about the general solution in this thread .
function getUserLocation(callback) { $.ajax('https://www.example.com/location.json', callback) } function getCurrentWeather(userLocation, callback) { $.ajax('https://www.example.com/weather' + userLocation + '.json', callback); } getUserLocation(function(user) { getCurrentWeather(user, function(weather) { console.log("Got weather", weather); }); });
source share