单击按钮时的增减变量-PHP Javascript AJAX

时间:2019-03-12 17:16:04

标签: javascript php toggle auto-increment decrement

我有一个“喜欢/不喜欢”按钮和“喜欢”数量字段,它回显一个获得“喜欢”数量的变量,如下所示:

PHP-HTML:

<a onclick="javascript:likes(<?php echo $row['Question_ID'];?>);"><button type="submit"  class="btn btn-custom btn-sm liketoggle" name ="like"><span>likes: <?php echo $row['likes'];?></span>
<button type="submit"  class="btn btn-custom btn-sm liketoggle" name ="like"></button></a>

//Printing 'Like' if its been liked by user, and 'Unlike' if not liked by user
<? $qid = $row['Question_ID']; $query2 = "SELECT * FROM likes WHERE 
       user_id='$user_id' and qid = '$qid'";
      $results2 = mysqli_query($con,$query2);
      if(mysqli_num_rows($results2) == 0){ echo '<span>Like</span>';} 
      else{echo '<span>Unlike</span>';}?></button>

AJAX:

function likes(qid) {

    if (ajax.readyState == 4 || ajax.readyState == 0) {
        ajax.open("POST", 'likes.php?qid='+qid, true);

        ajax.onreadystatechange = queried(type);
        ajax.send();
    }
}

Javascript-切换喜欢/不喜欢:

$(".liketoggle").click(function () {
            $(this).find("span").text(function(i, v){
               return v === 'Like' ? 'Unlike' : 'Like'
               return v === 'Unlike' ? 'Like' : 'Unlike'
            })
        });

有没有办法让用户点击喜欢时增加喜欢($ row ['likes'])的数量,并以相同的方式在不喜欢时减少喜欢的数量? 这怎么可能? AJAX正在数据库中完成这项工作,但我想更改前端的点赞次数。

1 个答案:

答案 0 :(得分:0)

尝试在您的范围内指定一个ID:

<span id="likes">likes: <?php echo $row['likes'];?></span>

然后在您的Ajax中,使用$('#likes')。html(response)将来自Ajax调用的响应放入该html标记中:

Ajax示例:

function likes(qid) {

    $.ajax({
        data: {qid: qid},
        type: 'POST',
        url: 'likes.php',
        success: function (response) {
            // Insert response into html
            $('#likes').html(response);
    }

}