0

I really don't know what I'm doing wrong here. I'm unable to reassign the variable poster_path with the poster-path fetched in the JSON-call. Now what surprises me is that I've tried to it async to false. And it didn't work.

I've searched through multiple existing answers such as this one (How do I return the response from an asynchronous call?) but haven't found any solution.

function getPoster(id) {
var poster_path = null;

$.getJSON( "https://api.moviedb.org"+id+"?", {async: false}, function( data ) { 
       poster_path = data.poster_path;
    }
}

PS: API-call has been shortened intentionally for this example. I know that it works and that it returns the correct data.

Community
  • 1
  • 1
user1531921
  • 1,372
  • 4
  • 18
  • 36
  • This might be helpful: https://stackoverflow.com/questions/14152276/themoviedb-json-api-with-jquery – Andy Jan 20 '14 at 03:03
  • 1
    The 2nd param is data, not options, see docs here http://api.jquery.com/jquery.getjson/. use $.ajax instead. – Andrew Jan 20 '14 at 03:06

1 Answers1

1

the $.getJSON function is a shorthand version of the $.ajax method. Because it is a shorthand version, it makes certain assumptions and one of them is that the call will be async.

If you want this to by a sync call which is not recommended then you want something like

$.ajax({
  'async'           : true,
  'dataType'        : 'json',
  'contentType'     : 'application/json',
  'url'             : 'https://api.moviedb.org'+id+'?',
  'success'         : function (data){ 
                        poster_path = data.poster_path;
                      }
});
jasonscript
  • 6,039
  • 3
  • 28
  • 43