Hey there! I've integrated the Youtube Player API and I'm handling certain actions based on the events triggered. Everything works smoothly when the video is playing or paused, but for some reason, the ended event never gets called. Instead, it triggers the paused event again. I'm fetching the video URL using a GET request from the URL bar, and that part is working perfectly.
<script>
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
//Load player api asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: get('url'),
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady(evt) {
// evt.target.playVideo();
}
function onPlayerStateChange(evt) {
if (evt.data == YT.PlayerState.PLAYING) {
$.ajax({ url:'insertToDBFromVid.php',
data: {action : 'playing' },
type: 'post',
done: function(result){
alert(result);
console.log("Success, Playing");
},
error: function(result){
alert(result)
console.log("Error in Playing");
}});
}
if (evt.data == YT.PlayerState.ENDED){
$.ajax({ url:'insertToDBFromVid.php',
data: {action : 'ended' },
type: 'post',
done: function(result){
alert(result);
console.log("Success, Ended");
},
error: function(result){
alert(result)
console.log("Error in Ended");
}});
}
if (evt.data == YT.PlayerState.PAUSED) {
$.ajax({ url:'insertToDBFromVid.php',
data: {action : 'paused' },
type: 'post',
done: function(result){
alert(result);
console.log("Success, Paused");
},
error: function(result){
alert(result)
console.log("Error in Paused");
}});
}
}
function stopVideo() {
player.stopVideo();
}
If anyone has insights on why this issue is occurring, your input would be greatly appreciated :)