So i am making an AJAX call (from youtube player javascript) to a php page which contains a few functions (mostly inserts into a db) and i am doing a case statement in my php to see in the post which function is being called.
Here is my php page containing the javascript where I make the Ajax call:
<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 done = false;
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 && !done) {
$.ajax({ url:'insertToDBFromVid.php',
data: {action : 'insertStart' },
type: 'post',
success: function (result){
alert(result);
}
});
}
if (evt.data == YT.PlayerState.PAUSED && !done) {
}
}
function stopVideo() {
player.stopVideo();
}
As you can see i get the video's id from the url line, this works fine.
And this is my php code that the Ajax call should be calling to:
<?php
require("config.php");
if(isset($_POST['action']) && !empty($_POST['action'])){
$action = $_POST['action'];
switch($action){
case 'insertStart' : insertStart(); break;
// case 'anotheraction' : anotheraction(); break;
}
}
function getUserID() {
$query = " SELECT 1 FROM users WHERE username = :username";
$query_params = array( ':username' => $_POST['username'] );
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$row = $stmt->fetch();
if($row){ echo "cant get user id" die("Cannot get User ID"); }
$row = $result->fetchObject();
$userid = $row->user_id;
}
function getVideoID() {
$query = " SELECT 1 FROM video WHERE url = :url";
$query_params = array( ':url' => $_GET["url"] );
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$row = $stmt->fetch();
if($row){ die("Cannot get Video URL"); }
$row = $result->fetchObject();
$videoid = $row->video_id;
}
function insertStart(){
getUserID();
getVideoID();
$query = " INSERT INTO session ( user_id, video_id) VALUES (
:userid, :videoid)";
$query_params = array( ':userid' => $userid, ':videoid' => $videoid );
}
?>
Can anyone see where I have went wrong?