php - 使用 AJAX 插入后选择

标签 php jquery mysql ajax select

我正在制作一个评论系统,除了一件事之外,我只拥有它的设置。现在,我使用 AJAX/PHP INSERT 评论,并在页面加载期间在评论页面上选择它。我无法弄清楚的是如何在我INSERT 评论之后SELECT 评论以使消息在不加载页面的情况下显示。

我已经完成了选择查询(在评论页面上),我可以将其添加到 php 文件并让 php 发回数据,或者我该怎么做?

我包含了我所有的代码来展示我现在拥有的系统。理想情况下,我希望将所有内容都保存在这些文件中,并有效地使用我拥有的任何代码。

我该怎么做?

评论页面的表单和SELECT查询:

<form action="" method="POST" id="comment-form">
            <label for="comment">Comment</label>
            <textarea cols="15" id="home_comment" name="comment" placeholder="Message" rows="5" maxlength="1000" required></textarea><br>
            <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
            <input id="comment-button" name="submit" type="submit" value="Post">
        </form>
<?php
$select_comments_sql = "
    SELECT * 
    FROM home_comments
    ORDER BY id DESC
";
  if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
        //$select_comments_stmt->bind_param("s", $user_id);
        $select_comments_stmt->execute();
        if (!$select_comments_stmt->errno) {
            //echo "error";
        }
        $select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date);

        $comment_array = array();
        while ($select_comments_stmt->fetch()) {
            $comment_array[] = $comment_user_id;
            $comment_array[] = $comment_username;
            $comment_array[] = $home_comments;
            $comment_array[] = $comment_date;
            if ($home_comments === NULL) {
                echo 'No comments found.';
            } else {
                echo $comment_username. "<br>";
                echo $home_comments. "<br><br><br>";
            }
        }   
  }

用于 INSERT 的 AJAX

$("#comment-form").on("submit", function (event) {
        event.preventDefault();

        var home_comment = $("#home_comment").val();

        $.ajax({ 
            url: "ajax-php/comment-send.php", 
            type: "POST",
            data: {
                "home_comment": home_comment
            },
            success: function (data) {
            //  console.log(data); // data object will return the response when status code is 200
                if (data == "Error!") {
                    alert("Unable to post comment!");
                    alert(data);
                } else {
                    $("#comment-form")[0].reset();
                    //$('.newsletter-popup').fadeIn(350).delay(2000).fadeOut();
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                alert(textStatus + " | " + errorThrown);
                console.log("error"); //otherwise error if status code is other than 200.
            }
        });
    });

INSERT 的 PHP 文件

$user = new User();

$home_comment = $_POST['home_comment'];
$username = $user->data()->username;
$okay = true;

if ( $okay ) { 

    $comment_insert = "
        INSERT INTO home_comments 
        (id, user_id, username, comment, date)
        VALUES(?, ?, ?, ?, NOW())
        ";
    $comment_stmt = $con->prepare($comment_insert);
    $comment_stmt->bind_param('ssss', $id, $user_id, $username, $home_comment);
    $comment_stmt->execute();
    }

最佳答案

请尝试如下

<ul id="CommentsList">
        <?php
    $select_comments_sql = "
        SELECT * 
        FROM home_comments
        ORDER BY id DESC
    ";
      if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
            //$select_comments_stmt->bind_param("s", $user_id);
            $select_comments_stmt->execute();
            if (!$select_comments_stmt->errno) {
                //echo "error";
            }
            $select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date);

            $comment_array = array();
            while ($select_comments_stmt->fetch()) {
                $comment_array[] = $comment_user_id;
                $comment_array[] = $comment_username;
                $comment_array[] = $home_comments;
                $comment_array[] = $comment_date;


                echo '<li>';
                    if ($home_comments === NULL) {
                        echo '<p>No comments found.</p>';
                    } else {
                        echo '<p>'.$comment_username.'</p>';
                        echo '<p>'.$home_comments.'<p>';
                    }
                echo '</li>';
            }  }  ?>  </ul>

在 Ajax 中:

成功后请添加以下代码

success: function (data) {
           $('#CommentsList').prepend(data);
    },

用于插入的 PHP 文件:

请在插入后添加以下代码(如有错误请更正以检索数据)($comment_stmt->execute();)

//Get the last insert id
    if($last_id = $comment_stmt->lastInsertId()){
        $sql = "SELECT * FROM home_comments where id=".$last_id;
        if ($select_comments_stmt = $con->prepare($sql)) {
            $select_comments_stmt->execute();
             $select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date);
             while ($select_comments_stmt->fetch()) {
              $comment_array[] = $comment_user_id;
                $comment_array[] = $comment_username;
                $comment_array[] = $home_comments;
                $comment_array[] = $comment_date;       
                echo '<li>';
                if ($home_comments === NULL) {
                    echo '<p>No comments found.</p>';
                } else {
                    echo '<p>'.$comment_username.'</p>';
                    echo '<p>'.$home_comments.'<p>';
                }
                echo '</li>';
             }
        }
    }

关于php - 使用 AJAX 插入后选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40155655/

相关文章:

javascript - 在命名处理函数中使用 $(this) 和事件

Django 中需要为特定元素而不是整个页面重新加载 JavaScript 函数

javascript - 如何使这个 slider 工作?

php - UTF-8贯穿始终

MySQL 订单表中订单商品的汇总价格

php - 特定 XMLHttpRequest 和 PHP 不允许 POST 405

php - 从 PHP 中的抽象父类访问子方法

MySQL Workbench 恢复数据库而不是导入数据

php - PHP 中有数学集的表示吗?

PHP查询以更新表中的字段