Updating global variables in javascript

140 views Asked by At

currently i'm working with the youtube api iframe, and i'm trying of do something when the video is ended, however, i need a global variable in javascript to continue. My code is like this:

var k =0

function onYouTubeIframeAPIReady() 
      {
          for(j=0;j<tam2;j++)
         {
          var nombre="player"+j;
          player = new YT.Player(nombre, 
          {
          height:'300',
          width:'580',
          videoId:arrayJS[j],
          events: {'onStateChange': onPlayerStateChange}
          });
        k++;
         }  
        }

So i need to identify each player in my onPlayerStateChange function, that is, get the index of my arrays arrayJS and arrayT to get the id and title of the specific video that is generating the finished event, I tried to do the following, but when I run console.log it says that the variable is not defined :

function onPlayerStateChange(event) 
     {
        if (event.data == YT.PlayerState.ENDED) 
        {
            console.log(k);
            $.ajax
            ({
                async:true,
                type: "POST",
                url:'v.php',
                data:
                {
                    idvideo:arrayJS[k],
                    titlevideo:arrayT[k]
                },
                success:function envio(deVuelta)
                {
                    alert(deVuelta);
                },
                timeout:30000,
                error:function()
                {
                    alert("Ocurrio un error");
                }
            });
        }
  }  
1

There are 1 answers

1
Tolgahan Albayrak On

Have you try bind ?

function onYouTubeIframeAPIReady() 
      {
          for(j=0;j<tam2;j++)
         {
          var nombre="player"+j;
          player = new YT.Player(nombre, 
          {
          height:'300',
          width:'580',
          videoId:arrayJS[j],
          events: {'onStateChange': onPlayerStateChange.bind(null, arrayJS, j)}
          });
        k++;
         }  
        }

function onPlayerStateChange(ary, idx, event) 
     {
        if (event.data == YT.PlayerState.ENDED) 
        {
            console.log(k);
            $.ajax
            ({
                async:true,
                type: "POST",
                url:'v.php',
                data:
                {
                    idvideo:arrayJS[k],
                    titlevideo:arrayT[k]
                },
                success:function envio(deVuelta)
                {
                    alert(deVuelta);
                },
                timeout:30000,
                error:function()
                {
                    alert("Ocurrio un error");
                }
            });
        }
  }