Piotr Berebecki Piotr Berebecki - 7 months ago 10
Javascript Question

Using jquery.when and done to pass a value from one ajax call to another

I'm trying to use the value from the first ajax call in the second ajax call. I'm using the code structure below. For some reason the second call returns

undefined
for the
userLocation
variable
. How could I refactor my code so that the userLocation value from the first ajax call can be used in the url of the second ajax call?

var userLocation;

function getUserLocation() {
$.ajax({
url: 'https://www.example.com/location.json',
success: function(response) {
userLocation = response.coordinates;
}
});
}

function getCurrentWeather() {
$.ajax({
url: 'https://www.example.com/weather' + userLocation + '.json',
success: function(response) {
console.log(response);
}
});
}


$(document).ready(function() {
$.when(
getUserLocation()
).done(
getCurrentWeather()
)
});


UPDATE 1:
Thanks to the answers provided below I've been able to refactor my code. Now the value received from the first ajax call can be used in the second ajax call. Here is the updated code:

var userLocation;

function getUserLocation() {
return $.ajax('https://www.example.com/location.json')
.then(function(response) {
return JSON.parse(response);
}).then(function(json) {
// data from the location.json file is available here
userLocation = json.coordinates;
})
}

function getCurrentWeather() {
return $.ajax('https://www.example.com/weather' + userLocation + '.json');
}


getUserLocation().then(getCurrentWeather).then(function(data) {
// data from the weather(userLocation).json file is available here
});

Answer

jQuery's 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, more verbosely

getUserLocation().then(function (user) { 
    return getCurrentWeather(user); 
}).then(function(data) {
   // location data here
});

The better solution would be to make it a single call rather than two calls since making a lot of AJAX calls slows down your application - especially on mobile devices with limited bandwidth.


Here is a callback based approach that is likely inferior to the promise based one (for example 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); 
   });
});