为什么我在 AJAX 中提交后会收到双重回复?

Why am I getting double reply after submitting in AJAX?

提问人:Razvan B 提问时间:11/14/2023 最后编辑:ADysonRazvan B 更新时间:11/14/2023 访问量:56

问:

我正在尝试为我的博客做一个评论回复系统。评论效果很好。当我第一次按下回复按钮时,它工作正常。如果我第二次按下它,它会使我对第二条评论的回复加倍。但是,当我在提交下一个回复之前刷新页面时,不会发生这种情况。

enter image description here

$(document).ready(function () {
    // When user clicks on submit comment to add comment under post
    $(document).on('click', '#submit_comment', function (e) {
        e.preventDefault();
        var comment_text = $('#comment_text').val();
        var url = $('#comment_form').attr('action');
        // Stop executing if not value is entered
        if (comment_text === "") return;
        $.ajax({
            url: url,
            type: "POST",
            data: {
                comment_text: comment_text,
                comment_posted: 1
            },
            success: function (data) {
                var response = JSON.parse(data);
                if (data === "error") {
                    alert('There was an error adding comment. Please try again');
                } else {
                    $('#comments-wrapper').prepend(response.comment)
                    $('#comments_count').text(response.comments_count);
                    $('#comment_text').val('');
                }
            }
        });
    });
    // When user clicks on submit reply to add reply under comment
    $(document).on('click', '.reply-btn', function (e) {
        e.preventDefault();
        // Get the comment id from the reply button's data-id attribute
        var comment_id = $(this).data('id');
        // show/hide the appropriate reply form (from the reply-btn (this), go to the parent element (comment-details)
        // and then its siblings which is a form element with id comment_reply_form_ + comment_id)
        $(this).parent().siblings('form#comment_reply_form_' + comment_id).toggle(500);
        $(document).on('click', '.submit-reply', function (e) {
            e.preventDefault();
            // elements
            var reply_textarea = $(this).siblings('textarea'); // reply textarea element
            var reply_text = $(this).siblings('textarea').val();
            var url = $(this).parent().attr('action');
            $.ajax({
                url: url,
                type: "POST",
                data: {
                    comment_id: comment_id,
                    reply_text: reply_text,
                    reply_posted: 1
                },
                success: function (data) {
                    if (data === "error") {
                        alert('There was an error adding reply. Please try again');
                    } else {
                        $('.replies_wrapper_' + comment_id).append(data);
                        reply_textarea.val('');
                    }
                }
            });
        });
    });
});

我试图在mysql中修改我的数据库,我担心第一次有问题。那里一切正常。 这是我的回复系统的代码:

// If the user clicked submit on reply form...
if (isset($_POST['reply_posted'])) {
        global $conn;
        // grab the reply that was submitted through Ajax call
        $reply_text = $_POST['reply_text']; 
        $comment_id = $_POST['comment_id']; 
        // insert reply into database
        $sql = "INSERT INTO replies (user_id, comment_id, body, created_at, updated_at) VALUES (" . $user_id . ", $comment_id, '$reply_text', now(), null)";
        $result = mysqli_query($conn, $sql);
        $inserted_id = $conn->insert_id;
        $res = mysqli_query($conn, "SELECT * FROM replies WHERE id=$inserted_id");
        $inserted_reply = mysqli_fetch_assoc($res);
        // if insert was successful, get that same reply from the database and return it
        if ($result) {
                $reply = "<div class='comment reply clearfix'>
                                        <img src='profile.png' alt='' class='profile_pic'>
                                        <div class='comment-details'>
                                                <span class='comment-name'>" . getUsernameById($inserted_reply['user_id']) . "</span>
                                                <span class='comment-date'>" . date('F j, Y ', strtotime($inserted_reply['created_at'])) . "</span>
                                                <p>" . $inserted_reply['body'] . "</p>
                                                <a class='reply-btn' href='#'>reply</a>
                                        </div>
                                </div>";
                echo $reply;
                exit();
        } else {
                echo "error";
                exit();
        }
}
php jquery mysql ajax

评论

5赞 CBroe 11/14/2023
因为在 的点击处理程序中,您每次都会添加一个额外的点击处理程序 - 因此每次点击后者都会被多次处理。.reply-btn.submit-reply
2赞 ADyson 11/14/2023
不知道你从哪里学习,但当你将用户输入合并到其中时,这是使用 PHP 构建 SQL 查询的完全错误的方法。1) 它容易受到 SQL 注入攻击,并且 2) 由于输入值,它可能会因简单的语法问题而崩溃 - 例如,任何在注释中带有 a 的人(例如单词)都会使您的查询崩溃,因为 SQL 会认为 在 .'don't'n
1赞 ADyson 11/14/2023
相反,您必须使用准备好的语句和参数来正确生成查询并安全地插入值。请参阅如何在MySQL语句中包含PHP变量,如何防止PHP中的SQL注入?以及 phpdelusions.net/mysqli 一些优秀的资源和如何正确执行此操作的简单示例。即使作为练习项目的初学者,您也应该养成良好的习惯。

答: 暂无答案