0
votes

So, first, I created a youtube search engine using javascript and youtube data API. Then I wanted to play the videos from the search results by clicking them. So I made a button for each result that passes the videoID variable to the playVideo() function (which swap the iframe link and refreshes it). But all the buttons in each result returns the same video ID which is the first result's video ID.
How to fix this?
this is my code:
thank you

//the search function
function search(){
    //clr results
    $('#results').html('');
    $('#buttons').html('');
    //get input val
    query = $('#query').val();
    //GET request on Youtube API V3
    $.get(
        "https://www.googleapis.com/youtube/v3/search",{
            part: 'snippet, id',
            q: query,
            type: 'video',
            key: my_apiKey},

            function(data){
                var nextPageToken = data.nextPageToken;
                var prevPageToken = data.prevPageToken;
                console.log(data);
                $.each(data.items, function(i, item){
                    //custom function to get request output
                    var output = getOutput(item);
                    $('#results').append(output);
                });
                //page buttons
                var buttons = pageBtn(prevPageToken, nextPageToken);
                $('#buttons').append(buttons);

            }
    );
}

//build the output
function getOutput(item){
    var vidId = item.id.videoId;
    var title = item.snippet.title;
    var img = item.snippet.thumbnails.high.url;

    var output ='<tr>' +
                '<td><img src="'+img+'" width="90px"/></td>'+
                '<td>'+title+' '+vidId+'</td>'+
                '<td><button id="play-video" data-url="http://www.youtube.com/embed/'+vidId+'?autoplay=1" onclick="playVideo();">Play</td>'+
                '</tr>';
    return output;
}
//play video
function playVideo(){
    var vidurl = $('#play-video').data('url');
    $("#player").html('<iframe type="text/html" width="640" height="390" src="'+vidurl+'" frameborder="0"></iframe>');
}
1
Must be related to pageBtn() post it or better if you post a jsfiddleVinay

1 Answers

1
votes

I managed to make it work by checking this related SO post. Here is my partial code:

vidIframe = '<button class="play-video" data-url="http://www.youtube.com/embed/'+item.id.videoId +'?autoplay=1" onclick="playVideo(this)">'+item.id.videoId +'</button>';


//play video
function playVideo(element){
    var vidurl = $(element).data('url');
    console.log(vidurl);
    $("#player").html('<iframe type="text/html" width="640" height="390" src="'+vidurl+'" frameborder="0"></iframe>');
}

The initial code got confused since all your target has the same id which I think will only get the value of the first index. In this updated code, even though they still have the same id value each call will get the attribute of the one performing the onclick event (indexed).