0

I am trying to store a YouTube title to a variable in this JavaScript function.

When I call the AddSong function the $.getJSON line displays the correct song title using the alert but when I try to use the variable named videoTitle is still has the initialized value of “Could Not Get Title.”

Why is it not returning the correct value? How can I change it to return the correct title?

function AddSong() {
    songCount++;
    $('#song-count').empty();
    $('#song-count').append('Song Count: ' + songCount);
    var url = createYouTubeEmbedLink($('#songTextBox').val()) + "?start=60&autoplay=1";
    var videoId = youtube_parser(url);
    var videoTitle = "Could Not Get Title";

    $.getJSON('http://gdata.youtube.com/feeds/api/videos/' + videoId + '?v=2&alt=jsonc', function (data, status, xhr)
    {
        alert(data.data.title);
        videoTitle = data.data.title;
    });

    $.ajax(
    {
        type: "Post",
        url: "@Url.Action("AddSong", "Game")",
        data: { SongURL: url, SongTitle: videoTitle },
        success: function (data) {}
    });
    $("#song-table").append("<tr><td>" + videoTitle + "</td></tr>");
}
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
user977154
  • 1,045
  • 4
  • 19
  • 39
  • You should put your append statement inside the getJSON compete function. Append is most likely being called before videoTitle is ever updated. – xd6_ Jun 13 '14 at 03:45
  • Also the `$.ajax` call should be in there. – Barmar Jun 13 '14 at 03:46

0 Answers0