6

I'm getting vimeo thumbnails from the API and I'm using a jQuery function to append the data to the dom.

I'm trying to access thumb_url outside ajax, so I can return it to jQuery, but it doesn't work.

function getThumb(vimeoVideoID) {
var thumb_url;

$.ajax({
    type: 'GET',
    url: 'http://vimeo.com/api/v2/video/' + vimeoVideoID + '.json',
    jsonp: 'callback',
    dataType: 'jsonp',
    success: function (data) {
        console.log(data[0].thumbnail_large);
        thumb_url = data[0].thumbnail_large;
    }
});
return thumb_url;
}

$('.video').each(function () {
var thumb_url = getThumb(this.id);
$(this).append('<img src="' + thumb_url + '" class="video_preview"/>');

});

Fiddle: http://jsfiddle.net/gyQS4/2/ help?

black_rabbit
  • 277
  • 2
  • 3
  • 10
  • possible duplicate of [How to return AJAX response Text?](http://stackoverflow.com/questions/1225667/how-to-return-ajax-response-text) – Quentin Jan 10 '14 at 19:01

1 Answers1

17

Because AJAX calls are asynchronous, you cannot return and access thumb_url the way that you're trying to.

In other words, because your AJAX call can get data at any time (it could take 1 second; it could take 10 seconds), the rest of the code (including the return statement) will execute synchronously, i.e. before the server even has a chance to respond with data.

A common design solution used in these situations is to execute whatever you want to execute inside of a callback function.

You could do something similar to this:

success: function (data) {
    console.log(data[0].thumbnail_large);
    thumb_url = data[0].thumbnail_large;

    //utilize your callback function
    doSomething(thumb_url);
}

/*     then, somewhere else in the code      */

//this is your callback function
function doSomething(param) {

    //do something with your parameter
    console.log(param);

}
Josh Beam
  • 19,292
  • 3
  • 45
  • 68
  • or like that, using done() method of promise interface: http://jsfiddle.net/xSKc8/ – A. Wolff Jan 10 '14 at 19:07
  • It logs the actualy image, but when I inspect the dom, I still get img src="undefined" . Still looks like var thumb_url has not been returned in the end http://jsfiddle.net/gyQS4/3/ – black_rabbit Jan 10 '14 at 19:28
  • You can't use a return statement here. You have to do everything inside the callback function. [See this jsfiddle](http://jsfiddle.net/gyQS4/4/) – Josh Beam Jan 10 '14 at 19:32