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条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题