1

I got a problem with my Json in Javascript. So I run json and I get a list of all youtube id's, now I show all those youtube videos and I place a button next to it. Now if I click that button it must give me a console log of the youtube id of that video but it always gives me the last youtube video id. Can anyobdy help me witht his code cause Im stuck.

Here is my code:

function generateLast5()
        {
        $("#musicList").html("");
        console.log("what uuup");
            $.ajax({
            url: ".............",       
            dataType: "jsonp",
            success: function(json){
                console.log(json.played_tracks);

                for(i in json.played_tracks)
                {
                    console.log(i);
                    oSingle = json.played_tracks[i];
                    console.log(oSingle.youtube_ids.default);

                    phli = $("<li/>") 
                        .appendTo("#musicList");

                    $("<iframe/>")
                        .attr("src", "http://www.youtube.com/embed/" + oSingle.youtube_ids.default)
                        .appendTo(phli);

                    $("<button/>")
                    .attr("id","btnAddToPlaylist")
                    .text("Add To Playlist")
                        .click(function() {
                         console.log(oSingle.youtube_ids.default);
                        })
                    .appendTo(phli);

                }       
            }

            });
}
user3011083
  • 67
  • 2
  • 10
  • I would store the id as an attribute on to the button (or somewhere else where you find it more suitable) and then read it in your console statement. 1) Store it. .data('track-id', oSingle.youtube_ids.default) 2) Read it. console.log($(this).data('track-id')). – Streamside Jan 13 '14 at 18:48
  • Obligatory, if somewhat redundant "DONT USE for..in TO ITERATE ARRAYS" goes here. – Alex Jan 13 '14 at 18:51
  • You might find it interesting to read up on scope in Javascript, here's a start; http://stackoverflow.com/questions/500431/javascript-variable-scope – hank Jan 13 '14 at 18:52
  • Thanks StreamSide that worked. If you could place it as an answer I can award it. – user3011083 Jan 13 '14 at 18:56

2 Answers2

1

There's a number of issues with your code.

First, you are creating multiple buttons that have the same id. ids should be unique (and in your case they are not needed).

Second, it is not recommended to use a for...in loop to iterate through arrays. Instead, use a for loop and the array length.

Third, you are assigning values to global variables. I would recommend local variables (e.g. var oSingle) to avoid conflicts.

Now to your issue: you always get the last id because that's what you are calling with oSingle.youtube_ids.default (cf. above comment on local variables). Instead, you could attach the id to each button:

$("<button/>")
  .data("youtubeId",oSingle.youtube_ids.default)
  .text("Add To Playlist")
  .click(function() {
    console.log($(this).data(youtubeId));
  })
Christophe
  • 27,383
  • 28
  • 97
  • 140
0

You should split your code up for better readability

AJAX Function

function generateLast5() {
    $("#musicList").html("");
    console.log("what uuup");
    $.ajax({
        url: ".............",
        dataType: "jsonp",
        success: function (json) {
            load(json); // call load function here
        }
    });
}

Loop with proper Array for loop and set id as data attribute

function load(json) {
    console.log(json.played_tracks);
    for ( var i = 0; i < json.played_tracks.length; i++) { // use array loop
        console.log(i);
        oSingle = json.played_tracks[i];
        console.log(oSingle.youtube_ids.default);

        phli = $("<li/>") 
            .appendTo("#musicList");

        $("<iframe/>")
            .attr("src", "http://www.youtube.com/embed/" + oSingle.youtube_ids.default)
            .appendTo(phli);

        $("<button/>")
            .data("id", oSingle.youtube_ids.default) // set id as data attribute
            .addClass('btn') // set class here for delegation reasons instead of id, Id should be unique
            .text("Add To Playlist")
            .appendTo(phli);
    } 
}

Separate click event

$('button').on('click', '.btn', function(){
    console.log($(this).data('id'));
});
dcodesmith
  • 9,590
  • 4
  • 36
  • 40