I am working with a website where I will have several embedded YouTube videos. I would like do two things.
- Attach a JavaScript listener to the videos to be able to tell if a video is played
- Send the corresponding data to a database using PHP
I understand that PHP will send the data server side, but I will already have the page loaded from JavaScript and the viewer may not resend a page to get that data into the database. My only other thought was AJAX, but I don’t have any experience with it.
I am thinking I should do something like this, but I am too new at JavaScript to know exactly how to implement this.
var video = document.getElementById('player1');
video.addEventListener("timeupdate", function() {
if (this.currentTime >= 0) {
//take in data from the video that it has been played
}
}, false);
Then I am still left with sending the data to my database.
I have not used the Youtube API before, but I believe the YouTube Javascript Player API is what you need.
player.getPlayerState()will tell you whether the player is playing, paused etc.player.getCurrentTime()will tell you the number of seconds since the player started playing.Once you have collected the data you need, send it to your server using AJAX. This part will depend on the javascript library you are using or whether you are just writing the javascript yourself. I like to use YUI (which is made by Yahoo!). I would craft a request using IO and send the data as encoded JSON or POST.
Then on the server side, the request would be received and then you can decode the JSON data into an array using
json_decode()or just get the data out of your$_POSTarray, get the values you require and pop them in your database.