0

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.

JAAulde
  • 19,250
  • 5
  • 52
  • 63
brx
  • 11
  • 2
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Apr 20 '17 at 14:30

2 Answers2

1

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);
Dennis
  • 646
  • 2
  • 6
  • 19
  • Thanks Dennis. It works like a charm, but I've modified it a bit. I've deleted var self = this; and set callback.call(this, data.city); Why do I need global var self? – brx Apr 21 '17 at 10:03
  • The anonymous function you are passing to jQuery will be called at some later point from another object or class. Usually that object does not have the same context as your current context. In case your `getTemperature()` function requires to access some data from your current context you would be in trouble. In order to bind your current context to the invocation we assign it before to a variable. In your case it works fine because everything is defined at the highest global namespace which is where variables and functions are picked up in case they are not found in the current context. – Dennis Apr 23 '17 at 20:29
0

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

Tomasz Kasperek
  • 1,147
  • 3
  • 13
  • 35