简体   繁体   English

PHP,MySQL和JQuery-更新表而不刷新页面

[英]PHP, MySQL and JQuery - Updating a table without refreshing page

On my site I have an "Add to favorites" / "Remove from favorites" button and an user can add/remove other users to/from his favorites. 在我的网站上,我有一个“添加到收藏夹” /“从收藏夹删除”按钮,用户可以将其他用户添加到他的收藏夹或从他的收藏夹中删除其他用户。

I have the table favorites with three columns: 我有三列的表favorites

+-------+-----------+------------------+
|  id   |  id_user  | id_favorite_user |
+-------+-----------+------------------+
|   1   |     13    |       70         |
|   2   |      7    |       48         |
|   3   |     12    |       89         |
|   4   |     13    |       56         | 
|   5   |     13    |       33         | 
|  ...  |    ...    |      ...         |
+-------+-----------+------------------+

in this example the user with the id 13 has three users at his favorites: 70, 56 and 33 在此示例中,id为13的用户在他的收藏夹中有三个用户:70、56和33

The following is the code of the link you click to add/remove from favorites and I have it on many pages: 以下是您单击以从收藏夹添加/删除链接的代码,我在很多页面上都看到它:

$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>
<? } ?> 

And here is the php script I use to update the table - addremovefavorites.php : 这是我用来更新表格的php脚本-addremovefavorites.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");
}
?>

This is how I have it now and it works but I don't like it. 这就是我现在拥有它的方式,并且可以运行,但是我不喜欢它。 When an user clicks on the link to add/remove to/from his favorites another user he adds/remove him, but then he is redirected to myfavorites.php and is very frustrating because he must click the "Back" button of his browser to go back to the page he was looking at before. 当用户单击链接以添加/删除他的收藏夹中的另一个用户时,他添加/删除了他,但是随后他被重定向到myfavorites.php,并且非常沮丧,因为他必须单击浏览器的“返回”按钮以回到他之前看过的页面。

Instead I want to do all this without the user leaving the current page. 相反,我想在用户不离开当前页面的情况下完成所有这些操作。 I want to update the table and then show a confirmation message that the user was added/removed to/from the favorites. 我想更新表,然后显示一条确认消息,表明用户已添加到收藏夹或从收藏夹中删除。

I need a hint from where to start. 我需要从哪里开始的提示。 I looked at the jQuery documentation here http://api.jquery.com/jQuery.ajax/ and this is how I approach it: 我在这里http://api.jquery.com/jQuery.ajax/上查看了jQuery文档,这就是我的处理方式:

<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>

for the links and: 链接和:

function clickHandler(type, userid){
$.ajax({
    type: "GET",
    url: "addremovefavorites.php",
    data: 'type='+ type + '&userid=' + userid,
    .done(function( msg ) {
    alert( "This user was " + msg);
    });
});
}

for the JQuery code. JQuery代码。

I would really appreciate any help you could give me regarding my script. 如果您对我的脚本有任何帮助,我将不胜感激。

Thanks! 谢谢!

Try this (untested). 试试这个(未试用)。 UPDATED. 更新。

function clickHandler(type, userid){
    $.ajax({
        type: "GET",
        url: "addremovefavorites.php",
        data: 'type='+ type + '&userid=' + userid,
        success: function(msg) {
            alert( "This user was " + msg);
        }
    });
}

Note that whatever appears in the alert - that is, the contents of var msg -- is whatever is echoed out at the end of addremovefavorites.php. 请注意,警报中出现的所有内容(即var msg的内容)都是在addremovefavorites.php结尾处回显的内容。

Therefore, if addremovefavorites.php ends with: 因此,如果addremovefavorites.php结尾为:

echo 'Bob is your uncle';

Then that is what will be the contents of the var msg in the success function. 这就是成功函数中var msg的内容。


However, it is always best to get rid of inline javascript. 但是,最好总是摆脱内联JavaScript。 Cleaner code, easier to maintain. 代码更清晰,更易于维护。

Change these: 更改这些:

<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>

To: 至:

<a href="#" id="add2fav" class="addrem">Add to favorites</a>
<a href="#" id="rem4fav" class="addrem">Remove from favorites</a>

In the jQuery: 在jQuery中:

$(document).on('click','#addrem', function() {
    var type = ( $(this).attr('id') == add2fav) ? 'add' : 'rem';
    var userid = "<?php echo $id_user_here; ?>"; //I am familiar with this syntax
    $.ajax({
        type: "GET",
        url: "addremovefavorites.php",
        data: 'type='+ type + '&userid=' + userid,
        success: function(msg) {
            alert( "This user was " + msg);
        }
    });
});

In your onclick attribute, the javascript is calling clickhandler with two arguments. 在您的onclick属性中,javascript正在调用带有两个参数的clickhandler。 The first argument in each call is currently a variable. 当前,每个调用中的第一个参数是一个变量。 I think you meant them to be strings? 我想你是说它们是字符串? Add apostrophes around addf and remf . addfremf周围添加撇号。

u can this with simple ajax: 你可以用简单的ajax来做到这一点:

<a href="javascript:void(0);" onclick="addremove('1')" id="1" data-user="1" data-type="add">add book</a>

where "1" the userid 其中“ 1”的用户ID

and the js: 和js:

function addremove(id){
        var user = $(id).attr('data-user'); 
            var type = $(id).attr('data-type'); 
        $.ajax({
                url: "addremove?type=" + type + "&user=" + user + "",
                beforeSend: function() {
                        $('#status').html('process...');
                },
                success: function(data){
                        $('#status').html(data);
                }
        });
}

@kamuken @kamuken

I presume you are already using this code and it's working. 我认为您已经在使用此代码,并且可以正常工作。 It did nothing and then I made this: 它什么也没做,然后我做到了:

<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function addremove(id){
    var user = $(id).attr('data-user');
    var type = $(id).attr('data-type');
    $.ajax({
            success: function(){
            alert('You want to ' + type + ' the user ' + user);
            }
    });
}
</script>
</head>
<body>

<a href="javascript:void(0);" onclick="addremove('54')" id="54" data-user="54" data-type="add">add book</a>

</body>

and I'm getting: "You want to undefined the user undefined" 我得到:“您想取消定义用户未定义”

I did it :) 我做的 :)

This is the code for my links: 这是我的链接的代码:

if ($totalRows_recordarray == 0) { ?>
     <a href="javascript:void(0);" onclick="addremove('add_<?= $id_user_here; ?>')" id="add_<?= $id_user_here; ?>">add to favorites</a>         <? } else { ?>
     <a href="javascript:void(0);" onclick="addremove('rem_<?= $id_user_here; ?>')" id="rem_<?= $id_user_here; ?>">remove from favorites</a></a>
<? } ?>

and this is the JQuery code: 这是JQuery代码:

<script type="text/javascript">
function addremove(id){
    var str = id;
var res = str.split("_");
    $.ajax({
    type: "GET",
    url: "addremovefavorites.php",
    data: { type: res[0], userid: res[1] }
})
.done(function( msg ) {
    alert( msg );
});
}
</script>

Now, it would be nice if instead of "add to favorites" i would have remove from favorites link after I add an user and "remove from favorites" link after I add him. 现在,如果我不是在添加用户后从“收藏夹”链接中删除,而是在添加用户后将“从收藏夹中删除”链接,而不是“添加到收藏夹”,那就太好了。 Any thoughts on this? 有什么想法吗?

Thank you all for the help. 谢谢大家的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM