0

"My question is different" edit: I am on about to export the variable rather than return it in callback function (which is what I am already doing).

I have a function that fetches data from url via jQuery ajax method. On success it calls the callback function that gets the data.

How can I now 'play' with the data?

The bigger picture is to update a chart based on data fetched, based on clicked button.

There will be different cities in URL Api, therefore the function / object will be called multiple times. Also the data I am getting will need manipulating and storing in variable.

What I have for now:

function getMainData(city, apiKey) {
  this.city = city;
  this.apiKey = apiKey;

  var url = "http://api.openweathermap.org/data/2.5/weather?q=";

  var ajaxUrl = url + city + apiKey;
  var mainData;

  $.ajax({
    method: "GET",
    type: "json",
    cache: false,
    url: ajaxUrl,
    success: myCallback
  });
};

function myCallback(data) {
  this.data = data;
  console.log(data);
};

var showMeData = getMainData("london", "&appid=7ce3e1102e1902e0f878c2a640e95aed");
user007
  • 45
  • 8
  • `this.data = data;` doesn’t make much sense in the callback, but you should be able to update the chart using the `data` variable from inside `myCallback`. – Ry- Mar 27 '18 at 14:07
  • I want to do out from outside of myCallback. Have a variable that I can throw anywhere. – user007 Mar 27 '18 at 14:08
  • `var myCities = {}; /* global var */ function getMainData(...) { ... success: function(data) { myCities[city]=data; processCity(city); }` – mplungjan Mar 27 '18 at 14:09
  • You can put the data outside of `myCallback`, but it still has to be responsible for continuing execution. – Ry- Mar 27 '18 at 14:10
  • https://jsfiddle.net/dh1u6tgp/7/ – mplungjan Mar 27 '18 at 14:17
  • I still don't get it... Maybe I am overengineering things. I would like to have an object/array that will contain fetched data and being accessible globally through many other functions / calls. I saw people tend to put ajax request inside 'on click' functions etc, but since I have multiple click items I do not want to DRY it... – user007 Mar 27 '18 at 14:26

0 Answers0