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
});