weixin_33691700 2019-01-20 13:32 采纳率: 0%
浏览 22

重新加载后Ajax结果不见了

I'm making a following system. If the user clicks on the follow button an ajax function is triggerd. The ajax function sends data to the actions.php file and this file checks if there is data in the database. Based on this info the code inserts the follower or deletes it from the database. This works fine! But for example if one user starts following the other person and than refresh the page the buttons html changes back to follow.

I have tried to do the result in php but it didn't work out

ajax:

$(".toggleFollow").click(function() {

    var id = $(this).attr("data-userId");

    $.ajax({
        type: "POST",
        url: "actions.php?action=toggleFollow",
        data: "userId=" + id,
        success: function(result) {

            if (result == "1") {

                $("button[data-userId='" + id + "']").html('<span class="icon icon-add-user"></span> Follow');

            } else if (result == "2") {

                $("button[data-userId='" + id + "']").html('<span class="icon icon-remove-user"></span> Unfollow');

            }
        }

    })

})

actions.php:

session_start();
require 'dbh.inc.php';
$id = $_SESSION['userId'];
$userId = $_POST['userId'];
if ($_GET['action'] == 'toggleFollow') {

    $query = "SELECT * FROM isFollowing WHERE follower = ". mysqli_real_escape_string($conn, $_SESSION['userId'])." AND isFollowing = ". mysqli_real_escape_string($conn, $_POST['userId'])." LIMIT 1";
        $result = mysqli_query($conn, $query);
        if (mysqli_num_rows($result) > 0) {

            $row = mysqli_fetch_assoc($result);

            mysqli_query($conn, "DELETE FROM isFollowing WHERE id = ". mysqli_real_escape_string($conn, $row['id'])." LIMIT 1");

            echo "1";

        } else {

            mysqli_query($conn, "INSERT INTO isFollowing (follower, isFollowing) VALUES (". mysqli_real_escape_string($conn, $_SESSION['userId']).", ". mysqli_real_escape_string($conn, $_POST['userId']).")");

            echo "2";


        }

}

I expect that the follow/unfollow button doesn't change after an refresh! PS This is my first question on stackoverflow!

  • 写回答

2条回答 默认 最新

  • weixin_33717298 2019-01-20 13:48
    关注

    I think you should using UPDATE query

    Wish code following:

    (1) -> Go url, load database 
    (2) -> Get statment is (none) Follow 
    (3) -> Ajax send
    (4) -> UPDATE statements (toggle) to unFollow
    (5) -> Response and change html 
    (6) -> Page refresh 
    (7) -> back to (1)
    

    With that, where Ajax send to actions.php, data is update inner you Database, and when refresh this page, you database reload perfect.

    评论

报告相同问题?