I make ajax request to the API:

function getImageURL(data) { var city = data; var link; //console.log(city); var requestURL = 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=dd7db2cb607c16d11c25c747acde0c06&format=json&nojsoncallback=1&sort=relevance&safe_search=1&per_page=1&text=' + city + '%20City'; //console.log(requestURL); $.ajax({ type: 'GET', url: requestURL, dataType: 'json', success: function(data) { //$('#test_block').append(JSON.stringify(data)); var json = data; link = 'https://farm' + json.photos.photo.farm + '.staticflickr.com/' + json.photos.photo.server + '/' + json.photos.photo.id + '_' + json.photos.photo.secret + '.jpg'; } }); console.log(link); } getImageURL('Kiev'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

In the body of success I am trying to generate a link from the resulting json string:

 {"photos":{"page":1,"pages":29667,"perpage":1,"total":"29667","photo":[{"id":"4451791182","owner":"35430600@N06","secret":"404c6073aa","server":"4058","farm":5,"title":"Kiev City","ispublic":1,"isfriend":0,"isfamily":0}]},"stat":"ok"} 

But when I try to output the value of the link variable to the console, I get undefined. How to fix it?

  • one
    undefined because you have declared a link variable with no value, and the jquery ajax request does not overwrite the external variable. I do not know how to overwrite an external variable. You also have an error when you receive a response in ajax, it should be so link = 'https://farm' + json.photos.photo [0] .farm + '.staticflickr.com/' + json.photos.photo [0 ] .server + '/' + json.photos.photo [0] .id + '_' + json.photos.photo [0] .secret + '.jpg'; - greybutton
  • one
    asynchronous - do not use the link variable before the success is executed - Igor
  • @greybutton - "ajax request does not overwrite the external variable" - overwrites, only this happens later than the console.log(link); . - Igor
  • @greybutton Perhaps I did not fully understand him. - Nicolas Chabanovsky

0