0

My basic requirement is that I can get a title of a youtube video so that I can access it and apply it to my page however I have hit a problem which I have tried to explain in the comments:

//first I declare my array and variable for the video information
var videoID = [];
var videoTitle;

//this ensures that the <div> exists
if ($("#productVideo0").length > 0) {

    //then for every occurrence of and embedded video...
    $(".youtube-video").each(function () {

        //I call this function which strips the video id out of the URL (in the array[1] element]
        videoID = getVideoID($(this).children().attr('src'));

        //then I make the JSON call
        $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + videoID[1] + '?v=2&alt=jsonc', function (data) {

            //if I alert this line below, it displays the title. 
            //However, if I try to alert or use this variable outside the function 
            //it just displays "undefined" or [object,object] depending on what I do
            videoTitle = data.data.title;
        })

    })
}

//this uses regex to strip the id from the url
function getVideoID(url) {
    url = url.match(/embed\/(\w*)/);
    return url;
}
Jason P
  • 26,984
  • 3
  • 31
  • 45
Greg
  • 187
  • 3
  • 15

2 Answers2

0

Why don't you try to append all the data.data.title into a list instead of replacing the entire variable each time? Maybe the last iteration is setting null to the videoTitle variable.

var videoID = [];
var videoTitle = [];

//this ensures that the <div> exists
if ($("#productVideo0").length > 0) {


    $(".youtube-video").each(function () {
        videoID = getVideoID($(this).children().attr('src'));

        //then I make the JSON call
        $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + videoID[1] + '?v=2&alt=jsonc', function (data) {


            videoTitle.push(data.data.title);
        })

    })
}
Raul M.S.
  • 245
  • 2
  • 7
0

The "data" json object is defined inside the function $.getJSON, once the function is ended the object will be destroyed. Try defining the data object outside and send it by reference to the getJSON. or better yet just don't call it from outside.

Aus
  • 1,183
  • 11
  • 27