0

i push data array i can see it in array but out of function there is no data in array why ??

function keyWordsearch() {

        var musicIDs = [];
        gapi.client.setApiKey('AIzaSyB2O-w22OSJVSKPhAYsK_zxX7FsThM0mhE');
        gapi.client.load('youtube', 'v3', function () {
            idlist = '';


            var q = $('#querySerach').val();
            $("#result").empty();
            var request = gapi.client.youtube.search.list({
                q: q,
                part: 'snippet',
                maxResults: 3,

            });

            request.execute(function (response) {

                for (var i = 0; i < response.items.length; i++) {

                    var musicid2 = response.items[i].id.videoId;

                    musicIDs.push(musicid2);

                   // i push data array i can see it in array but  out of function there is no data in array why ?? ------

                    var pID = '#myPlayerID';
                    var ratio = '4/3';

                }

            });

        });
        alert(musicIDs[1]); // here is musicID[1] return undefined

}

Anonymous0day
  • 3,012
  • 1
  • 14
  • 16

1 Answers1

1

Ajax calls are asynchronous, so you have to do the alert inside the response function where the api is called. In this case inside the request.execute(function (response) {

request.execute(function (response) {

            for (var i = 0; i < response.items.length; i++) {

                var musicid2 = response.items[i].id.videoId;

                musicIDs.push(musicid2);

                var pID = '#myPlayerID';
                var ratio = '4/3';

            }

            alert(musicIDs[1]);
}

More info here

Community
  • 1
  • 1
Carlos Mayo
  • 2,054
  • 1
  • 19
  • 35