Passing data outside ajax call, jQuery

black_rabbit picture black_rabbit · Jan 10, 2014 · Viewed 18.6k times · Source

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?

Answer

Josh Beam picture Josh Beam · Jan 10, 2014

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);

}