brx
brx

Reputation: 11

Use AJAX response as var outside of function

I need to pass data from AJAX response. Here's the code:

function getLocation() {
    $.get('https://ipinfo.io/json', function (data) {
        console.log(data);
        $('.test').html('<h2>Your location is: ' +  data.city + '.</h2>');  
    });
}
getLocation();

It's working ok, but I want to use data.city as variable, which I can pass to other api request, to get temperature for this city. I'm on the very begining of js/jQuery development, so any help would be appreciated.

Upvotes: 0

Views: 1060

Answers (2)

Dennis
Dennis

Reputation: 696

You are in an asynchronous context so you cannot simply use return values. One way is to chain actions by providing the respective callback functions.

var self = this;

function getLocation(callback) {
  $.get('https://ipinfo.io/json', function (data) {
      console.log(data);
      $('.test').html('<h2>Your location is: ' +  data.city + '.</h2>');  
      callback.call(self, data.city);
  });
}

function getTemperature(location) {
  //do another AJAX call here to get temperature and modify your DOM
}

getLocation(getTemperature);

Upvotes: 1

Tomasz Kasperek
Tomasz Kasperek

Reputation: 1187

It's an asynchronous callback. So if you want to use it later, for example for another AJAX call, then you should make next call inside your callback:

function getLocation() {
    $.get('https://ipinfo.io/json', function (data) {
        console.log(data);
        $('.test').html('<h2>Your location is: ' +  data.city + '.</h2>');

        // Use your data here for another AJAX call
        $.get('https://example.com/test?city=' + data.city, function () {});  
    });
}
getLocation();

You might as well look for Promises later to deal with async code more in more elegant manner. https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Promise

Upvotes: 0

Related Questions