0

Why does currentT not change value until after loop in the ajax statement within the function GetSongs(id). I debugged and the value will not change values while it is looping.

var currentT = "test";
    function GetSongs(id) {
        $.ajax(
        {
            type: "Get",
            url: "@Url.Action("GetSongs", "Game")",
            data: { playlistId : id },
            success: function (data) {
                json = data;
                var obj = JSON.parse(json);
                for (var i in obj) {
                    var videoId = youtube_parser(obj[i].SongURL);
                    getVideoInformation(videoId);
                    $("#song-table").append("<tr><td>" + currentT.toString() + "</td></tr>");
                    playlist.push(obj[i].SongURL);
                }

            }
        });
    }

    function youtube_parser(url) {
        var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
        var match = url.match(regExp);
        if (match && match[7].length == 11) {
            return match[7];
        } else {
            alert("Url incorrecta");
        }
    }

    function registerScript(url) {
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.src = url;
        document.getElementsByTagName('head')[0].appendChild(s);
    }

    function videoInfoCallback(info) {
        if (info.error) {
            alert('Error\n\n' + info.error.message);
        } else {
            var message = info.data.title;
            currentT = message;
            return message;
        }
        return "Parser Error";
    }

function getVideoInformation(id) {
        return registerScript('https://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=jsonc&callback=videoInfoCallback');
}
user977154
  • 1,045
  • 4
  • 19
  • 39
  • Welcome to the wonderful world of **async**! You can't do that. – SLaks Apr 29 '14 at 00:21
  • Is there any way around this? – user977154 Apr 29 '14 at 00:22
  • 1
    It's only being set in a callback, so it's going to be set *asynchronously* when the callback is invoked. Whatever you want to do with the information in the callback needs to be done in response to the callback itself, not immediately after the asynchronous operation is invoked. There's no guarantee if/when the callback will be reached. – David Apr 29 '14 at 00:24

0 Answers0