简体   繁体   中英

PHP no results message still showing when posting data via ajax

I'm creating a comment facility for a blog post using PHP and ajax to post the comment so the page does not refresh after a comment is posted.

This is the code that displays the comments when the page is visited. If there are no comments for the post it displays a notice. This all works.

$stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
                        FROM comments comm
                        JOIN members m
                            ON comm.member_id = m.id
                        WHERE comm.entry_id = ?
                        ORDER BY comm.comment_date DESC");
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt_result = $stmt->get_result();

if ($stmt_result->num_rows > 0) {
    while($row = $stmt_result->fetch_assoc()) {
        $comment = $row["comment"];
        $comment_date =  date_create($row['comment_date']);
        $comment_date = date_format($comment_date, ' l jS F Y H:i');
        $comment_author = $row["member_screen_name"];

        $comments .= "<div class='comment_div'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";
    }
}else{
    $comments = "<div class='alert alert-primary' role='alert'>Be the first to comment</div>";
}

When the comment form is submitted it calls this function.

$('#submit').click(function (e) {
    e.preventDefault();
    if (!$('#summernote').summernote('isEmpty')) {
        var comment = document.getElementById("summernote").value;
        var member_id = 1;
        var post_id = 1;
        $.ajax ({
            type: 'post',
            url: 'post_comment.php',
            data: {
                comment:comment,
                member_id:member_id,
                post_id:post_id,
            },
            success: function (response) {
                document.getElementById("all_comments").innerHTML=response+document.getElementById("all_comments").innerHTML;
                $("#summernote").summernote("reset");
            },
        });
    }else {
        alert('Please enter a comment');
    }
    return false;
}); 

This is the post_comment.php page

if(isset($_POST['comment'])){
    $comments = "";
    $comment=$_POST['comment'];
    $member_id =$_POST['member_id'];
    $post_id =$_POST['post_id'];
    if(isset($comment)) {
        $stmt = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
        $stmt->bind_param("iis", $post_id, $member_id, $comment);   
        $stmt->execute();
        $entry_id = mysqli_insert_id($conn);

        $stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
                                FROM comments comm
                                JOIN members m
                                   ON comm.member_id = m.id
                                WHERE comm.entry_id = ?
                                   AND comm.id = $entry_id
                                ORDER BY comm.comment_date DESC");
        $stmt->bind_param("i", $post_id);
        $stmt->execute();
        $stmt_result = $stmt->get_result();

        if ($stmt_result->num_rows > 0) {
            while($row = $stmt_result->fetch_assoc()) {
                $comment = $comment;
                $comment_date =  date_create($row['comment_date']);
                $comment_date = date_format($comment_date, ' l jS F Y H:i');
                $comment_author = $row["member_screen_name"];

                $comments .= "<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by $comment_author on $comment_date</p>$comment<hr /></div></div>";

                echo $comments ;
             };
            exit;
        }
    }
}else {
    header("location: /blog");
    exit;
}

If you are the first to comment on a post the comment displays but the "Be the first to comment" notice is still displaying until the page is refreshed.

Try return the response from the server as json. Plus remove the exit and header on your server side.

<script type="text/javascript">
    $('#submit').click(function (e) {
        e.preventDefault();
        if (!$('#summernote').summernote('isEmpty')) {
            var comment = document.getElementById("summernote").value;
            var member_id = 1;
            var post_id = 1;
            $.ajax ({
                type: 'post',
                url: 'post_comment.php',
                data: {
                    comment:comment,
                    member_id:member_id,
                    post_id:post_id,
                },
                dataType : "json",
                encode   : true,
                success: function (data) {
    $.each(data, function(index, element){ 
$('#all_comments').append("<div class='comment_div' style='background:red'><div class='small'><p class='text-info'>posted by " +element.comment_author + "on " + element.post_date+"</p>"+element.comment+"<hr /></div></div>"); 
}); 

$("#summernote").summernote("reset"); 
$('.alert').empty();
                },
            });
        }else {
            alert('Please enter a comment');
        }
        return false;
    });
</script>

Then your server side.

 <?php
if (isset($_POST['comment'])) {
    $comment       = $_POST['comment'];
    $member_id     = $_POST['member_id'];
    $post_id       = $_POST['post_id'];
    $commentsArray = array();
    $stmt          = $conn->prepare("INSERT INTO comments (entry_id, member_id, comment) VALUES (?, ?, ?)");
    $stmt->bind_param("iis", $post_id, $member_id, $comment);
    $stmt->execute();

    $entry_id = mysqli_insert_id($conn);

    $stmt = $conn->prepare("SELECT comm.comment, comm.comment_date, m.member_screen_name
                                FROM comments comm
                                JOIN members m
                                ON comm.member_id = m.id
                                WHERE comm.entry_id = ?
                                AND comm.id = ?
                                ORDER BY comm.comment_date DESC");
    $sql->bind_param("ii", $post_id, $entry_id);
    $sql->execute();
    $sql_result = $sql->get_result();

    if ($stmt_result->num_rows > 0) {
        while ($row = $stmt_result->fetch_assoc()) {
            $comment_date =  date_create($row['comment_date']);
            $commentsArray[] = array(
                'comment' => $comment,
                 'post_date' = date_format($comment_date, ' l jS F Y H:i');
                'comment_author' => $row['member_screen_name']
            );
        }

    }


    echo json_encode($commentsArray);
}

Also use the network tab on your browser console to see the response coming from the server.

it is normal for him to behave like this, and at no time will you ask the notification not to appear after the comment.

update your code after the success

$('.alert-primary').hide()

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