weixin_33739541 2015-04-26 18:43 采纳率: 0%
浏览 41

Ajax调用数据库PHP

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?

  • 写回答

1条回答 默认 最新

  • weixin_33744141 2015-04-26 19:18
    关注

    One major issue is your variables are undefined in insertStart(). Even if they were you never process the actual insert or send any response to browser.

    You are calling getUserId() and getVideoId() but not assigning the return values to anything. Then you introduce undefined variables into the query params array

    Try changing to:

    function insertStart(){
        //declare the 2 variables first using return values of associated functions
        $userid  = getUserID();
        $videoid = getVideoID();
    
    
        $query = " INSERT INTO session ( user_id, video_id) VALUES ( 
                    :userid, :videoid)"; 
        $query_params = array( ':userid' => $userid, ':videoid' => $videoid ); 
     // now do the insert and send response to browser
    
    }  
    

    Now the function still isn't doing anything with the query params or returning anything or generating any output so you need to finish doing the actual insert and send back response data.

    overall I suggest you revisit all your logic step by step

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度