简体   繁体   中英

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

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

For some reason the second call returns undefined for the userLocation variable

This is because you are not returning the promise from the ajax call, see Benjamin's answer on how to do this.

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?

Refactor your code to nest the call to the other function inside the first call:

var userLocation;

function getUserLocation() {
  $.ajax({
    url: 'https://www.example.com/location.json',
    success: function(response) {
      // set the user location
      userLocation = response.coordinates;
      // make call to second function passing in userLocation
      getCurrentWeather(userLocation);
    }
  });
}

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

$(document).ready(function() {
    getUserLocation()
});

If your not using the variable userLocation anywhere else then save a bit of code:

function getUserLocation() {
  $.ajax({
    url: 'https://www.example.com/location.json',
    success: function(response) {
      // make call to second function passing in coordinates from response
      getCurrentWeather(response.coordinates);
    }
  });
}

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

$(document).ready(function() {
    getUserLocation()
});

You should be doing this:

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

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


$(document).ready(function() {
  $.when(
    getUserLocation()
  ).done(
    getCurrentWeather
  )
});
  1. return the $.ajax(...) from getUserLocation
  2. getCurrentWeather is pass as a function, you shouldn't call it in the done, it will called async after getUserLocation is done.

Edit #2 : What you are doing wrong in puting getCurrentWeather() into the .done(...) is that this function will call immediately. However, .done(...) should passed in a function, where the function will be called after the $.when() promise is resolved.

As Benjamin Gruenbaum mentioned, it is better to use .done(...) then .then(...)

It can be like this :

var userLocation;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM