[英]AJAX update MYSQL database using function called from HTML generated from PHP
[英]Update database with html link click using ajax php mysql
我已经阅读了许多类似的问题,并尝试将其在我的网站上工作,但是它不起作用(当您单击链接时,控制台上没有响应,并且数据库也没有更新)。
我要执行的操作是:我希望用户通过单击评论旁边的图标为评论+1
评分。 我想要那更新我的mysql comment_table
列,称为rating
为rating+1
。 当我在没有AJAX的情况下执行此操作时(即,仅将表单操作设置为php page?id=10
)就可以正常工作。 我无法通过AJAX更新数据库。
我的主页上有评论:
<a href="javascript:void(0);" onClick="updateRating(1,<?php echo $thisperspective_row['id']; ?>)" alt="UPVOTE" id="upvote_<?php echo $thisperspective_row['id']; ?>"><span class="glyphicon glyphicon-chevron-up"></span></a>
该链接下方的javascript:
<script type="text/javascript">
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
rating: rating,
id: <?php echo $thisperspective_row['id']; ?>,
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
</script>
而我的rating.php文件是
<?php
require_once('connectiontodatabase.php');
/* simple comment up and down voting script */
$mode = $_GET['mode'];
$rating = $_GET['rating'];
$id = $_GET['id'];
if ($mode=="vote")
{
// The name of the
$cookie = "nameofmycookie".$id;
if(isset($_COOKIE[$cookie]))
{
echo '<div class="alert alert-warning"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Sorry You have already rated this comment within the last 14 days.</div>';
}
else
{
$expiry = 1209600 + time(); // 14 day expiry
setcookie ($cookie, "voted", $expiry);
mysql_query ("UPDATE comment_table SET rating = rating+$rating WHERE id=$id", $connection);
}
}
?>
php运行正常,当我查看源代码时,所有变量均正确列出。 但是,当我单击链接时,根本没有响应,控制台也不会输出响应。 我究竟做错了什么? 提前致谢!
首先,您应该更改检测点击事件的方式。 看看这个小提琴 。 其次,您需要使用data选项将所有变量传递到一个JSON字符串中 。 您的代码应如下所示:
<span class="glyphicon glyphicon-chevron-up clickable"
data-rating="1"
data-id="<?php echo $thisperspective_row['id']; ?>"></span>
<script type="text/javascript">
$('.clickable').on('click', function() {
var data = {
mode: "vote",
rating: $(this).data('rating'),
id: $(this).data('id')
};
$.ajax({
type: 'GET',
url: 'rating.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
</script>
首先,请检查您是否正在加载jQuery,然后使用此代码
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
data: { rating: rating, id: id },
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
为我工作。 请注意,我在Ajax内删除了`,因为您已经在函数中发送了参数,并且还必须使用data:来发送参数,您可以在此处看到更多示例Ajax jQuery
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.