Return a boolean from a PHP file to the AJAX one - Follow button

后端 未结 1 1348
庸人自扰
庸人自扰 2021-01-29 02:42

I\'m creating a follow button, more or less like the twitter one.

You click the button, and you follow the user.

1条回答
  •  长情又很酷
    2021-01-29 03:11

    There are numerous problems here. For one, like @Mark said, you need to understand that when sending ajax requests to PHP, you are sending strings. Also, in your JS, you are binding a click function to the .heart.canal, but then the function changes all elements with that class rather than the actual clicked element. Lastly, once you send the right information to PHP you need to print your results in order to see it in ajax.

    Try the following:

    JS:

    $(document).ready(function () {
        $(".heart.canal").click(function () {
            var $heart = $(this);
            if ($heart.data("following")) {
                $heart.data("following", false)
            } else {
                $heart.data("following", true);
            }
    
            var usuario = $(".left").find("h4").data("id");
            var seguidor = $("#user_account_info").find(".profile_ball").data("id");
    
            $.ajax({
                type: "POST",
                url: "follow.php",
                data: {user: usuario, follower: seguidor, follow: $heart.data("following")},
                success: function (result) {
                    if (result) {
                        console.log("true");
                    } else {
                        console.log("false");
                    }
                }
            });
            return false;
    
        });
    
    });
    

    PHP:

    $user = (int)$_POST["user"];
    $seguidor = (int)$_POST["follower"];
    $follow = ($_POST["follow"] === 'true') ? true : false;
    
    if ($follow) {
        // insert
    } else {
        // delete
    }
    
    print $follow;
    

    0 讨论(0)
提交回复
热议问题