douba1498 2014-10-10 16:00
浏览 57
已采纳

完整页面加载完成后,jQuery AJAX无法更新数据库

This is my first time using jQuery AJAX so bear with me. I am trying to create a like button for my website similar to the Facebook like button. A user must be logged on via Facebook which will pull their userid from my database. When a user clicks on the like button, it inserts a row into the database with the user info and the page info. If there is already an entry for the user and page, it will update the row.

My code runs perfectly fine on my localhost. I can click on the like button all day and the image will constantly change back and forth from like to unlike and back. The database updates every time as well with no problem.

When I upload this to my live server, the script runs perfectly fine as well to a point. Once my page finishes loading completely, the database no longer updates from the click. The images will change as usual and I will receive the alert('Success') but no changes are made to the actual database.

<?php
$tempstat = '1';
if ($stmt = $mysqli -> prepare("SELECT count(id)
    FROM votes
    WHERE businessid=? and status=? ")) {
    $stmt -> bind_param('ss', $businessid, $tempstat);
    $stmt -> execute();
    $stmt->bind_result($likecount);
    $stmt->fetch();
    $stmt->close();
}
if ($likecount == '') { $likecount = 0; }
?>
<style>
#karmabar { padding-left: 4px; }
#counter { margin: 0 auto; text-align: center; width: 50px; height: 25px; background-image: url('/images/karma-counter.png'); }
p#counter { font-size: 12px; padding-top: 5px; }
.karma { margin: 0 auto; font-size: 16px; color: blue; text-align: center; padding: 5px; }
</style>
<?php
if(login_check($mysqli) == true) { 
$userid = $_SESSION['userurl']; 
if ($stmt = $mysqli -> prepare("SELECT status
    FROM votes
    WHERE userid=? and businessid=? ")) {
    $stmt -> bind_param('ss', $userid, $businessid);
    $stmt -> execute();
    $stmt -> bind_result($like_status);
    $stmt->fetch();
    $stmt->close();
}
if ($like_status == '' or $like_status == NULL) { $like_status = '0'; }
?>

<script type="text/javascript">
  $(document).ready(function() {
    $('#like_post').click(function() {
      $.ajax({
        url: "/includes/like.php",
        type: "GET",
        data: 'userid=<?php echo $userid; ?>&businessid=<?php echo $businessid; ?>&like_status=1',
        success: function() {
            alert("Success");
        },
        error: function() {
           alert("Something went wrong");
        }
      });
      $('#counter').html(function(i, val) { return val*1+1 });
      $('#like_post').hide();
      $('#unlike_post').show();
    });

  $('#unlike_post').click(function() {
     $.ajax({
        url: "/includes/like.php",
        type: "GET",
        data: 'userid=<?php echo $userid; ?>&businessid=<?php echo $businessid; ?>&like_status=0',
        success: function() {
            alert("Success");
        },
        error: function() {
            alert("Something went wrong");
        }
        });
      $('#counter').html(function(i, val) { return val*1-1 });
      $('#unlike_post').hide();
      $('#like_post').show();
  });
});
</script>
<div id="karmabar">
    <table cellpadding="0px">
        <?php if ($like_status == '0') { ?>
        <tr><td><a href="javascript:;" id="unlike_post" class="hide"><img src="/images/karma-active.png" title="Undo Karma" /></a><a href="javascript:;" id="like_post"><img src="/images/karma-inactive.png" title="Spread Karma" /></a><td><p id="counter"><?php echo $likecount; ?></p></td></tr>
        <?php } else { ?>
        <tr><td><a href="javascript:;" id="unlike_post"><img src="/images/karma-active.png" title="Undo Karma" /></a><a href="javascript:;" id="like_post" class="hide"><img src="/images/karma-inactive.png" title="Spread Karma" /></a></td><td><p id="counter"><?php echo $likecount; ?></p></td></tr>
        <?php } ?>
    </table>
</div>
<?php } else { ?>
<div id="karmabar">
    <table cellpadding="0px">
        <tr><td><a href="#" onclick="alert('Login with Facebook to Spread Karma');" ><img src="/images/karma-inactive.png" title="Spread Karma" /></a><td><p id="counter"><?php echo $likecount; ?></p></td></tr>
    </table>
</div>

$businessid and $userid are both defined higher up on the page.

like.php

<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/includes/functions.php';
$userid = $_GET['userid'];
$businessid = $_GET['businessid'];
$IP = $mysqli->real_escape_string(getClientIP());
$like_status = $_GET['like_status'];
if ($stmt = $mysqli -> prepare("SELECT count(id)
    FROM votes
    WHERE userid=? and businessid=? ")) {
        $stmt -> bind_param('ss', $userid, $businessid);
        $stmt -> execute();
        $stmt ->bind_result($count);
        $stmt ->fetch();
        $stmt ->close();
}
if ($count == '1') {
    if ($stmt = $mysqli -> prepare("UPDATE votes 
    SET ip=?, status=?
    WHERE userid=? and businessid=? ")) {
        $stmt -> bind_param('ssss', $IP, $like_status, $userid, $businessid);
        $stmt -> execute();
        $stmt -> close();
        $mysqli -> close();
    }
}
if ($count == '0') {
    if ($stmt = $mysqli -> prepare("INSERT INTO votes (userid, businessid, ip, status) 
    VALUES ( ?, ?, ?, ? ) ")) {
        $stmt -> bind_param('ssss', $userid, $businessid, $IP, $like_status );
        $stmt -> execute();
        $stmt -> close();
        $mysqli -> close();
    }
}
?>

I appreciate any help that you guys can give me. Like I said, I'm new to this kind of coding and looking for any pointers that you may have.

  • 写回答

2条回答 默认 最新

  • duanao4503 2014-10-10 20:59
    关注

    Mike, I'm not sure what's going on, but maybe you can try using this type of ajax request / PHP returns to trouble shoot:

    Replace your entire AJAX function with this:

    $(document).ready(function() {
        $('#like_post').click(function() {
            $.post("/includes/like.php", {userid:<?php echo $userid; ?>, businessid:<?php echo $businessid; ?>, like_status:"1"}, function(data){
                alert(data); //Check to see what is being returned
                if(data == 1){ //Later, you can echo "1" in your PHP file on success
                    //This is success
                    alert("Success");
                    $('#counter').html(function(i, val) { return val*1+1 });
                    $('#like_post').hide();
                    $('#unlike_post').show();
                } else {
                    //This is failure
                    alert("Failure");
                }
            });
        });
    
        $('#unlike_post').click(function() {
            $.post("/includes/like.php", {userid:<?php echo $userid; ?>, businessid:<?php echo $businessid; ?>, like_status:"0"}, function(data){
                alert(data); //Check to see what is being returned
                if(data == 1){ //Later, you can echo "1" in your PHP file on success
                    //This is success
                    alert("Success");
                    $('#counter').html(function(i, val) { return val*1-1 });
                    $('#unlike_post').hide();
                    $('#like_post').show();
                } else {
                    //This is failure
                    alert("Failure");
                }
            });
        });
    });
    

    And here would be the PHP - Notice, I changed your $_GETs to $_POSTs and added an echo at the end. I explain why after.

    <?php
        include_once $_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php';
        include_once $_SERVER['DOCUMENT_ROOT'].'/includes/functions.php';
        $userid = $_POST['userid'];
        $businessid = $_POST['businessid'];
        $like_status = $_POST['like_status'];
        $IP = $mysqli->real_escape_string(getClientIP());
        if ($stmt = $mysqli -> prepare("SELECT count(id) FROM votes WHERE userid=? and businessid=? ")) {
            $stmt -> bind_param('ss', $userid, $businessid);
            $stmt -> execute();
            $stmt ->bind_result($count);
            $stmt ->fetch();
            $stmt ->close();
            echo "Got the count: " . $count;
        }
        if ($count == '1') {
            echo "The Count is 1";
            if ($stmt = $mysqli -> prepare("UPDATE votes SET ip=?, status=? WHERE userid=? and businessid=? ")) {
                $stmt -> bind_param('ssss', $IP, $like_status, $userid, $businessid);
                $stmt -> execute();
                $stmt -> close();
                $mysqli -> close();
                echo "And the post is successful (1)";
            }
        }
        if ($count == '0') {
            echo "The Count is 0";
            if ($stmt = $mysqli -> prepare("INSERT INTO votes (userid, businessid, ip, status) VALUES ( ?, ?, ?, ? ) ")) {
                $stmt -> bind_param('ssss', $userid, $businessid, $IP, $like_status );
                $stmt -> execute();
                $stmt -> close();
                $mysqli -> close();
                echo "And the post is successful (0)";
            }
        }
        echo "finished";
    ?>
    

    Basically - I've added in a bunch of echos that you will be able to 'listen' to with your $.post ajax call when it returns the data. If everything is successful, you should get a sentence returned saying something like "Got the count: 1TheCount is 1 And the post is successful(1)Finished". All of those echos should fire when the post is successful. If you don't get one of those sentences, something has gone wrong.

    Try this to trouble shoot and let us know what comes back.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False