我正在尝试使用jQuery和AJAX来表示喜欢,当我点击表情符号时,该值在数据库中就会增加。但是我必须刷新页面才能看到更新的值。
最初,我以为id是有问题的,我了解到HTML中的id属性应该以[a-zA-Z]开头。我修好了现在无法解决计数器动态更新的问题。
下面是要显示类似计数器的div。
<div class="article-left-box">
<div class="article-left-box-inner">
<div class="article-share">
<a href="#" class="facebook"></a>
<a href="#" class="twitter"></a>
</div>
<span class="add-to-favorite" data-zebra-tooltip title="Ad to favorite">
<i class="material-icons"></i>
</span>
<ul class="article-emoticons">
<li><a class="popular happy"></a><span><?php echo $row["total_reactions"]; ?></span>
<ul>
<li><a id=<?php echo $row['news_id']?> class="love" style='cursor:pointer;'></a><span><?php echo $row["love_reactions"]; ?></span></li>
<li><a class="shocked" style='cursor:pointer;'></a><span><?php echo $row["shocked_reactions"]; ?></span></li>
</ul>
</li>
</ul>
</div>
</div>
下面是jQuery
$(document).ready(function(){
$(".love").click(function(){
var idofpost=$(this).attr('id');
//alert(idofpost);
$.ajax({
type:'POST',
url:'reactions.php',
data:'id='+idofpost,
success:function(data)
{
$(this).children().first().html(data);
}
});
});
});
下面是Reactions.php
<?php
include 'dbconnection.php';
$id = $_POST['id'];
$sql = "UPDATE news_mst SET love_reactions = love_reactions + 1 WHERE news_mst.news_id = '$id'";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
$sql = "SELECT love_reactions from news_mst WHERE news_mst.news_id = '$id'";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
//$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?>