我試圖通過點擊使用AJAX的鏈接來更新MySQL,但我已經打了一堵牆。我有代碼但它不工作。SQL更新通過A HREF
這裏的AJAX:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//bind a listener to "click" event on links with class "markviewed"
$('a.markviewed').click(function(event) {
//prevent default behavior just in case
event.preventDefault();
//get ids from clicked <a>
var myid = $(this).attr('data-myid');
var postid = $(this).attr('data-postid');
//ping the address to mark clicked link as viewed
$.ajax('http://mywebsite.com/mark_viewed.php?myid=' + myid + '&postid=' + postid');
//redirect to the link in the href attribute
window.location.href = $(this).attr('href');
});
});
</script>
這應該創建一個A HREF類,當點擊命中mywebsite.com/mark_viewed.php與發送爲$myid
和$postid
關鍵變量更新我的數據庫。
這裏是mark_viewed.php:
<?php
$con=mysqli_connect("XXX","XXX","XXX","XXX");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// get values sent from address bar
$myid=$_GET['myid'];
$postid=$_GET['postid'];
mysqli_query($con,"UPDATE comments SET status='viewed' WHERE to_id ='$myid' AND id='$postid'");
mysqli_close($con);
?>
最後,這是用戶看到的鏈接:
$myid = $row['user_id']; // my id
$name = $row['board_name']; // collection name
$boardid = $row['board_id']; // collection id
$postid = $row['pin_id']; // post id
$url = $row['pin_url']; // image url
echo "<li><a href='/board/pins/$boardid/$postid' data-myid=' . $myid . ' data-postid=' . $postid . ' class='markviewed'>";
echo "<img src='$url' height='50' width='50'>";
echo "New comment in $name.";
echo "</a></li>";
然而,在測試中這是行不通的。點擊時的鏈接只是與新評論和數據庫衝突到頁面。
我在做什麼錯?
刪除'window.location.href = $(this).attr('href');' – putvande
您的ajax調用是否被創建?如果是這樣發生了什麼,你是否得到一個錯誤? – PugFugly
您應該,不需要..在查詢中使用之前,您需要驗證/清除您的$ myid和$ postid變量。請記住,用戶輸入是EVIL! – Babblo