在我的網站上,我有一個「添加到收藏夾」/「從收藏夾中刪除」按鈕,用戶可以向他的收藏夾中添加/刪除其他用戶。PHP,MySQL和JQuery - 更新表格而不刷新頁面
我有表favorites
有三列:
+-------+-----------+------------------+
| id | id_user | id_favorite_user |
+-------+-----------+------------------+
| 1 | 13 | 70 |
| 2 | 7 | 48 |
| 3 | 12 | 89 |
| 4 | 13 | 56 |
| 5 | 13 | 33 |
| ... | ... | ... |
+-------+-----------+------------------+
在該示例
用戶id爲13在他的收藏夾三個用戶:70,56和33
以下是代碼鏈接的點擊添加/從收藏列表中刪除,我有它的許多頁面:
$my_user_id = $_SESSION['account']['id'];
//We test if the user $my_user_id has the user $id_user_here to his favorites or not. If he already has it we show a "Remove user from favorites" link, if not an "Add to favorites" link
$query = "SELECT `id` FROM `favorites` WHERE `id_user` = '$my_user_id' AND `id_favorite_user` = '$id_user_here' ";
$result = mysql_query($query) or die(mysql_error());
$row_result = mysql_fetch_assoc($result);
$totalrows_result = mysql_num_rows($result);
if ($totalrows_result == 0) { ?>
<a href="addremovefavorites.php?type=addf&userid=<?= $id_user_here; ?>" title="Add to favorites"><img src="images/addtofavorites.gif"></a>
<? } else { ?>
<a href="addremovefavorites.php?type=remf&userid=<?= $id_user_here; ?>" title="Remove from favorites"><img src="images/removefromfavorites.gif"></a>
<? } ?>
這裏是PHP腳本我用它來更新表 - addremovefavo rites.php:
<?php
//Here we connect to the database and check if the user is logged in...
$my_user_id = $_SESSION['account']['id'];
$type = testforsqlinjections($_GET['type']);
$userid = testforsqlinjections($_GET['userid']);
if ($type == "addf") {
$query = "SELECT * FROM `favorites` WHERE id_user='$my_user_id' AND id_favorite_user='$userid' ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result)<0) {
$query = "INSERT INTO `favorites` (`id_user`, `id_favorite_user`) VALUES ('$my_user_id', '$userid')";
$result = mysql_query($query) or die(mysql_error());
header("location: myfavorites.php");
}
}
if ($type == "delf") {
$query = "DELETE FROM `favorites` WHERE `id_user` = '$my_user_id' AND `id_favorite_user` = '$userid' ";
$result = mysql_query($query) or die(mysql_error());
header("location: myfavorites.php");
}
?>
這就是我現在如何使用它,但它的工作原理,但我不喜歡它。當用戶點擊鏈接添加/刪除他的收藏夾時,他添加/刪除了他,但是他被重定向到myfavorites.php,並且非常令人沮喪,因爲他必須點擊瀏覽器的「後退」按鈕回到他以前看過的頁面。
相反,我想要做所有這些,而無需用戶離開當前頁面。我想更新表格,然後顯示一條確認消息,表明用戶已添加到收藏夾或從收藏夾中移除。
我需要從哪裏開始提示。我看着jQuery的文檔這裏http://api.jquery.com/jQuery.ajax/,這是我如何處理它:
<a href="#" onclick="javascript:clickHandler(addf, <?= $id_user_here; ?>); return false;">Add to favorites</a>
<a href="#" onclick="javascript:clickHandler(remf, <?= $id_user_here; ?>); return false;">Remove from favorites</a>
的鏈接和:
function clickHandler(type, userid){
$.ajax({
type: "GET",
url: "addremovefavorites.php",
data: 'type='+ type + '&userid=' + userid,
.done(function(msg) {
alert("This user was " + msg);
});
});
}
的jQuery代碼。
我真的很感謝你能給我關於我的劇本的任何幫助。
謝謝!
你在正確的軌道上。你無法解決的問題是什麼,你的代碼不工作? – anthonygore