简体   繁体   中英

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:

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

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

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:

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

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.

Therefore, if addremovefavorites.php ends with:

echo 'Bob is your uncle';

Then that is what will be the contents of the var msg in the success function.


However, it is always best to get rid of inline 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:

$(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. The first argument in each call is currently a variable. I think you meant them to be strings? Add apostrophes around addf and remf .

u can this with simple ajax:

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

where "1" the userid

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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