【问题标题】:Ajax does not display data from database when 'reply comment' button is clicked on单击“回复评论”按钮时,Ajax 不显示数据库中的数据
【发布时间】:2019-07-31 20:00:44
【问题描述】:

我正在开发一个发布/回复评论系统。该帖子使用 Ajax、jquery 和 Php 从数据库发送和显示数据。

用于插入和显示来自数据库的帖子的 Ajax 运行良好。用于将评论/回复插入数据库的 Ajax 也可以正常工作,但用于显示对这些帖子的评论/回复的 ajax 不起作用。

当我回复帖子时,它不会立即显示,除非我刷新页面,即我会看到评论/回复文本。

//where post retrieved from database displays.

<div class="panelchat panel" id="postRows"></div>   

// Ajax for inserting and displaying post.

 $("#post-form-id").on('submit', (function(e) {

    e.preventDefault();     

    $.ajax({
    url: "forumAjax.php",
    type: "POST",
    data:  new FormData(this),
    contentType: false,
    cache: false,
    processData:false,
    success: function(data) {
    $("#post-form-id")[0].reset(); 
    $("#previewImg").hide();
    }       
    });
    displayPost();
    $("#post-form-id")[0].reset(); 


 }));


function displayPost() {
    $.ajax({
        url: "forumAjax.php",
        type: "POST",
        async: false,
        data: {
        "postDisplay" : 1
        }, 
        success: function(data) {

        $("#postRows").html(data);
        oneClickFunc();
        }
    });     
    replyFunc();
}
displayPost();



function oneClickFunc() {

        $("label.replyText").one("click", function() {

        var comCode = $(this).attr("name");
        var parent = $(this).parent();
        parent.append("<br /><form action='' method='POST' id='replyForm'><a href='#' class='imgLink'><img src='resources/images/why5.png' class='reply-image' /></a><textarea class='reply-textarea' name='replyTextarea' id='commentReply' autocorrect='on' spellcheck='spellcheck' maxlength='500' placeholder='Write a reply...'></textarea><input type='hidden' name='code' value='"+comCode+"' /><input type='submit' class='form-submit' id='replyBtn' name='ReplyBtn' value='Send' /></form><br />");

        autosize(document.getElementById("commentReply"));

        replyFunc();        
    });

}



function replyFunc() {

        $("#replyForm").on('submit', (function(e) {
        e.preventDefault();

        $.ajax({
        url: "forumAjax.php",
        type: "POST",
        data:  new FormData(this),
        contentType: false,
        cache: false,
        processData:false,
        success: function(data) {
            $("#replyForm")[0].reset(); 
        }     
        });
        postReplyDisplay();
    }));


    }

replyFunc();


function postReplyDisplay() {

    $.ajax({
    url: "forumAjax.php",
    type: "POST",
    async: false,
    data: {
        "newReplyx" : 1
    },
    success: function(data) {
        console.log(data);
    }, 
    error: function(jqXHR, textStatus, errordata) {
        alert(errordata);
    }
}); 
}
postReplyDisplay();



//Php code that inserts and retrieves data from database.

if(!empty($_POST['replyTextarea'])) {


    $userReply = $mysqli->escape_string($_POST['replyTextarea']);
    $userID = $mysqli->escape_string($_SESSION['user_id']);
    $replyDate = date('Y-m-d H:i:s');
    $replyCode = $_POST['code'];

    $INSERT = "INSERT INTO forumreply (reply, replyDate, codeMatch) VALUES(?, ?, ?)";
    $stmt = $mysqli->prepare($INSERT);
    $stmt->bind_param("sss", $userReply, $replyDate, $replyCode);
    $stmt->execute();

}



if(isset($_POST["postDisplay"])) {

    $email = $mysqli->escape_string($_SESSION['email']);

    $result = "SELECT * FROM forum ORDER BY user_id DESC";
    $Chatresult = $mysqli->query($result);

    if($Chatresult->num_rows > 0) {

        while($rows = $Chatresult->fetch_assoc()) {

            $image = $rows["image"];
            $postContent = $rows["post"];
            $datePosted = new dateTime($rows["postDate"]);
            $datePosted = date_format($datePosted, 'M j, Y | H:i:s');
            $postCode = $rows['code'];

                echo '<br /><div id="'.$postCode.'" class="postSeparator">';
                    echo '<a href="#"><img src="resources/images/passport1.jpg" title="CLEAN WATER" class="q-pic"></a>';
                    echo '<span class="name"><a href="#">Mariela Collazo</a></span>';
                    echo '<span class="postDate">'.$datePosted.'</span>';

                    if(isset($_SESSION['logged_in']) != 1) {
                    echo '';
                    } else {
                    echo '<span class="add-user edit-post"><i class="fas fa-edit"></i><ul class="editPost"><li>Edit post</li><li>Delete &nbsp;<i class="far fa-trash-alt"></i></li><li>Report post <i class="far fa-flag"></i></li></ul>
                    </span>'.'<span id="addUser" class="add-user"><i class="fas fa-user-plus"></i>&nbsp;<span class="text">Follow</span>
                    </span>';
                    }

if($image === "") { echo "";
} 
else { echo '<a href="resources/images/forum/'.$image.'" target="_blank"><img src="resources/images/forum/'.$image.'" alt="" class="post-picture"></a>';
                        }

if($postContent !== '') {
echo '<textarea class="post" readonly="true" id="#" autocorrect="off">'.stripslashes($postContent).'</textarea>';
} else {echo '';
}

echo '<div class="activity-wrapper" id="'.$postCode.'">';

echo '<label class="replyText" name="'.$postCode.'"><i class="far fa-comment-alt"></i>&nbsp;&nbsp;&nbsp;&nbsp;Reply</label>|
                        <span class="thumbsUp" title="Like"><i class="fas fa-thumbs-up"></i>&nbsp;<span class="reply-counter">7</span></span>&nbsp;<span class="times"><i class="fas fa-times" title="Dislike"></i>&nbsp;<span class="reply-counter">3</span></span> <br />';


$result = "SELECT * FROM forumreply WHERE codeMatch = '$postCode' ORDER BY replyDate DESC";
                $replyResult = $mysqli->query($result);
                $childContent = $replyResult->num_rows;


                if($childContent == 0) {
                    echo '<label class="commentLabel" name="'.$postCode.'">Comments (<span class="reply-counter">'.$childContent.'</span>) </label><br />';

                } else {

                    echo '<label class="commentLabel" name="'.$postCode.'">Comments (<span class="reply-counter">'.$childContent.'</span>) </label><br />';
                    echo '</div><br />'; 


echo '<div id="child-comments" id="C-'.$postCode.'">';

    foreach($replyResult as $com) {
                        $childDate = new dateTime($com['replyDate']);
                        $childDate = date_format($childDate, 'M j, Y | H:i:s');
                        $chiCom = $com['reply'];



echo '<div class="child postReplyx" id="'.$postCode.'-C">'
                                .'<a href="#"><img src="resources/images/passport1.jpg" class="userPic"></a>'
                                .'<span class="time">'.$childDate.'</span>'
                                .'<span class="options"><i class="fas fa-ellipsis-h"></i><ul class="actions"><li>Edit reply</li><li>Delete &nbsp;<i class="far fa-trash-alt"></i></li></ul></span>'
                                .'<div class="comment-text">'.stripslashes($chiCom).'</div>'.'<div id="emoji-options"><span class="fontAwesome" title="Like"><i class="fas fa-thumbs-up"></i><span class="counter">4</span></span><span class="fontAwesome" title="Dislike"><i class="fas fa-times"></i><span class="counter">4</span></span></div>'
                            .'</div>';

                    }

                    echo '</div>'; 

                } 


                        echo '</div>';  

        echo '</div>';


     }
   }
}

【问题讨论】:

    标签: php jquery html ajax


    【解决方案1】:

    您调用 postReplyDisplay() 函数太快了。请记住,ajax 是异步的,这意味着它会在脚本继续运行时完成其工作。您正在显示结果,而 ajax 尚未完成更新。将 postReplyDisplay() 移到replyFunc() 的成功内。

    function replyFunc() {
    
            $("#replyForm").on('submit', (function(e) {
            e.preventDefault();
    
            $.ajax({
               url: "forumAjax.php",
               type: "POST",
               data:  new FormData(this),
               contentType: false,
               cache: false,
               processData:false,
               success: function(data) {
                  $("#replyForm")[0].reset();
                  postReplyDisplay(); 
               }     
            });        
        }));
    }
    

    【讨论】:

    • 感谢您的回复 Nawed Khan。我已经这样做了,但除非刷新页面,否则回复文本不会立即显示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多