单击js链接/按钮后如何将记录发送到表格?

时间:2016-02-29 05:10:00

标签: javascript php html ajax mysqli

我想在帖子下面制作一个不喜欢的按钮。注册用户可以给予喜欢。我已经制作了按钮,但我不知道如何在用户点击按钮时发送记录。我想我需要like表,所以下面是表格和我所拥有的字段:

userid_userusername

postingid_postid_usercontent

likeid_likeid_userid_post

发布页面和类似按钮脚本:

<?php
include "database_connection.php";
$query=$dbc->query("select user.username, posting.content FROM posting inner join user on user.id_user = posting.id_user where id_post='$_GET[id]'");
$array= $query->fetch_array()
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="post.js"></script>
</head>
<body>
<?php echo $array['username'];?>
    <?php echo $array['content'];?>
<!--THIS IS LIKE BUTTON-->
  <a class="like-button" href="#"><i class="fa fa-thumbs-up"></i></a>
<!--LIKE BUTTON END-->
</body>
</html>

post.js

$(function() {
    $('.like-button').click(function(){
        var obj = $(this);
        if( obj.data('liked') ){
            obj.data('liked', false);
            obj.html('<i class="fa fa-thumbs-up"></i>');
        }
        else{
            obj.data('liked', true);
            obj.html('<i class="fa fa-thumbs-down"></i>');
        }
    });
});

3 个答案:

答案 0 :(得分:1)

好的,所以我花了很多时间为你创建一个基本的工作示例。

为了简单起见,我在内联脚本中包含了post.js的工作方式而不是单独的文件,并在脚本中包含了一个PHP变量。

您的HTML页面

<?php
include "database-connection.php";
$user = 1;// get your accessing user ID (not user id of poster)
$post = $_GET['id'];
// query checks whether user has liked the post or not and returns it as well
$query=$dbc->prepare("
    SELECT `user`.`username`, `posting`.`content`, IFNULL(`like`.`id_like`,0) AS `id_like`
    FROM `posting`
    INNER JOIN `user` ON `user`.`id_user` = `posting`.`id_user`
    LEFT JOIN `like` ON `like`.`id_user` = ? AND `like`.`id_post` = ?
    WHERE `posting`.`id_post`=?");
// bind the parameters to avoid injection
$query->execute(array($user, $post, $post));
$array= $query->fetch(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
        <script type="text/javascript">
            // previously post.js
            $(function() {
                $('.like-button').click(function(e){
                    e.preventDefault();
                    var obj = $(this);

                    // ajax query that returns a JSON object with the result of the request
                    $.getJSON('likes.php',{post:obj.data('post'), user: <?php echo $user; ?>}, function(data){
                        //console.log(data); // uncomment for debugging
                        if(data.error){
                            // query returned error, handle it however you want
                        } else {
                            if (data.like == 1){ // user now likes the post
                                obj.html('<i class="fa fa-thumbs-up"></i>');
                            } else { // user now doesn't like the post
                                obj.html('<i class="fa fa-thumbs-down"></i>');
                            }
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <?php echo $array['username'];?>
        <?php echo $array['content'];?>
        <!--THIS IS LIKE BUTTON-->
        <?php
        if ($array['id_like']==0){
            // user hasn't liked the post, show thumbs down
            echo '<a class="like-button" href="#" data-post="'.$post.'"><i class="fa fa-thumbs-down"></i></a>';
        } else {
            // user has liked the post, show thumbs up
            echo '<a class="like-button" href="#" data-post="'.$post.'"><i class="fa fa-thumbs-up"></i></a>';
        }
        ?>
        <!--LIKE BUTTON END-->
    </body>
</html>

likes.php(PHP脚本)

<?php
include "database-connection.php";
$post = $_GET['post'];
$user = $_GET['user'];
$result = (object) ['like'=>null, 'post'=>$post, 'user'=>$user];
$q = $dbc->prepare("SELECT id_like FROM `like` WHERE id_post=? AND id_user=?");
$q->execute(array($post, $user));
$r = $q->fetch(PDO::FETCH_OBJ);
if ($q->rowCount() > 0){
    $like = $r->id_like;
} else {
    $like = 0;
}
if ($like == 1){
    // user likes post, so we unlike it by setting id_like to 0 (for false)
    $like = 0;
    $u = $dbc->prepare("UPDATE `like` SET id_like = 0 WHERE id_post=? AND id_user=?");
} elseif ($q->rowCount()>0) {
    // update because the record exists
    $like = 1;
    $u = $dbc->prepare("UPDATE `like` SET id_like = 1 WHERE id_post=? AND id_user=?");
} else {
    // create the record because it doesn't exist yet
    $like = 1;
    $u = $dbc->prepare("INSERT INTO `like` (id_like, id_post, id_user) VALUES(1, ?, ?)");
}

if($u->execute(array($post, $user))){
    // update succeeded
    $result->like = $like;
} else{
    // there was an error
    $result->error = 'failed to execute in database';
}
// return the json object to your page
echo json_encode($result);

同样,这只是它如何工作的基础知识。您必须自己研究登录,会话和安全性,以管理正在访问,发布和喜欢内容的用户。但我希望这有帮助!

答案 1 :(得分:0)

点击like按钮将请求发送到PHP页面并在那里处理以更新数据库。

答案 2 :(得分:-1)

您需要向服务器发送Ajax请求,然后在PHP脚本中处理。

这是一种方法。

post.js

$(function() {
    $('.like-button').click(function(){
        var obj = $(this);
        if( obj.data('liked') ){
            obj.data('liked', false);
            obj.html('<i class="fa fa-thumbs-up"></i>');
        }
        else{
            obj.data('liked', true);
            obj.html('<i class="fa fa-thumbs-down"></i>');
        }
        $.post('url/to/your_script.php', {
          action: 'updateLikeStatus', 
          status: obj.data('liked'),
          post_id: obj.data('id') // ID of the object that user "liked"
        });
    });
});

您可以阅读有关jQuery.post() here的更多信息。关于更一般的jQuery.ajax()方法的here's文档。

your_script.php(处理Ajax请求的脚本)可能如下所示:

<?php
include "database_connection.php";

if (isset($_POST['action']) && $_POST['action'] === 'updateLikeStatus') {
    $id_user = $_SESSION['user_id'];
    $id_post = $_POST['post_id'];

    if ($_POST['status'] === true) {

      // adding "like"
      $query = $dbc->query("
        INSERT INTO like
        (id_user, id_post)
        VALUES ({$id_user}, {$id_post});
      ");
      $query->query();
    } else {

      // removing "like"
      $query = $dbc->query("
        DELETE FROM like 
        WHERE id_user = {$id_user}
        AND id_post = {$id_post};
      ");
      $query->query();
    }
}

请注意,此代码只是一个示例,您不应该直接在生产中使用它。首先,您不能将$_POST中的变量直接放入MySQL查询中,因为它会创建一个SQL注入类型漏洞,允许人们在您的服务器上执行任意查询。避免它的一种方法是使用prepared statements

另一个问题是您需要处理用户身份验证和授权。我在我的示例中使用了$_SESSION['user_id'],但除非您初始化会话并首先填充user_id值,否则它将无效。会话是必需的,以便一个用户不能代表另一个用户喜欢帖子。你可以read more about sessions here