-1
var a = 0;
var requestStr ="https://api.flickr.com/services/rest/?method=flickr.interestingness.getList&format=json&nojsoncallback=1&per_page=20&api_key=dc140afe3fd3a251c2fdf9dcd835be5c"; //flickr key.
$.get(requestStr, function(data){
    a = data;
});

console.log(a);

This prints out 0, but im trying to save the data parameter into the global variable a.

I've tried a self invoking function and using a 2nd function to set a = data, but they don't work.

Honestly can't figure this out.

zzzzz
  • 75
  • 2
  • 10

2 Answers2

1

You need to have promise:

$.get(requestStr, function(data){
    a = data;
}).always(function(){
    console.log(a);
});

Because $.get() method is async call, so the response take time to come and the execution of js codes gets executed.

Other than this you might want to take a look at $.when().

Jai
  • 74,255
  • 12
  • 74
  • 103
0

Ajax calls are asynchronous, which means a = data; gets called after console.log(a);, because fetching data from web takes time.

You need to process data when the data actually arrives:

var a = 0;
var requestStr ="https://api.flickr.com/services/rest/?method=flickr.interestingness.getList&format=json&nojsoncallback=1&per_page=20&api_key=dc140afe3fd3a251c2fdf9dcd835be5c"; //flickr key.
$.get(requestStr, function(data){
    a = data;
    console.log(a);
});
gre_gor
  • 6,669
  • 9
  • 47
  • 52