Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
});
like image 606
Piotr Berebecki Avatar asked Apr 24 '16 07:04

Piotr Berebecki


People also ask

Can jQuery and ajax be used together?

What About jQuery and AJAX? jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

Can we call two ajax inside ajax?

Function ajax can only make one Ajax call. A callback function is executed when the Ajax call is successful. Optionally, another callback function is called when the Ajax call returns an error.

Can you explain the difference between jQuery get () and jQuery ajax ()?

get() executes an Ajax GET request. The returned data (which can be any data) will be passed to your callback handler. $(selector). load() will execute an Ajax GET request and will set the content of the selected returned data (which should be either text or HTML).

What is get and post method in ajax?

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.


1 Answers

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); 
   });
});
like image 154
Benjamin Gruenbaum Avatar answered Nov 09 '22 22:11

Benjamin Gruenbaum