soum
soum

Reputation: 1159

separate get requests for each youtube video ID

I am trying to pass in each id from an array holding youtube IDs to a get request. The goal is to get names for each video ids and create a new array.

To start with this is what I am doing. I am getting an empty array

var x = ['CSvFpBOe8eY', 'Zi_XLOBDo_Y'];
var x_title = [];

for (var i = 0; i < x.length; i++) {
    $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + x[i] + '?v=2&alt=jsonc', function (data, status, xhr) {
        x_title[i]= data.data.title;
    });    
}

console.log(x_title)

Here is the fiddle

http://jsfiddle.net/sghoush1/Cnepk/5/

Upvotes: 0

Views: 36

Answers (2)

subhaze
subhaze

Reputation: 8855

The array is blank because it's getting printed out before all the getJSON calls are complete. But, you have another issue as well.

i is not scoped for each loop so you'll end up using the last value of i by the time the requests are completed.

You'll need to wrapper the inner loop with and IIFE (Immediately Invoked Function Execution) and pass i into it, or, use the forEach api of the Array.

Example of using IIFE http://jsfiddle.net/jj7Pg/

for (var i = 0; i < x.length; i++) {
    (function(_i){
        $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + x[_i] + '?v=2&alt=jsonc', function (data, status, xhr) {
            x_title[_i]= data.data.title;
            console.log(x_title);
        }); 
   }(i));
}

Example of forEach http://jsfiddle.net/jj7Pg/1/

x.forEach(function(item, indx){
    $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + item + '?v=2&alt=jsonc', function (data, status, xhr) {
        x_title[indx]= data.data.title;
        console.log(x_title);
    });
});

I would go with the forEach approach if you're working with newer browsers. Compatibility list can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Browser_compatibility

Upvotes: 2

danjam
danjam

Reputation: 1062

This is actually working fine but you are getting an empty array because your getJSON call is asynchronous and your console.log is firing before it has returned data.

Example fiddle, note the work is done inside the success callback function.

Upvotes: 2

Related Questions