weixin_33725807 2016-10-20 13:20 采纳率: 0%
浏览 25

用AJAX插入后选择

I am making a comment system and I have it just about setup, other than one thing. Right now I INSERT the comment with AJAX/PHP and select it on the comment page during page load. The item I cannot figure out is how to SELECT the comments after I INSERT them to enable the message to appear without page loading.

I have the select query already made up (on the comments page), can I just add that to the php file and have php send back the data or what do I do?

I am including all of my code to show the system I have now. Ideally I would like to keep everything within these files and efficiently use any code I have.

How can I do this?

Form and SELECT query on the comments page:

<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>";
            }
        }   
  }

AJAX for INSERT

$("#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.
            }
        });
    });

PHP file for INSERT

$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();
    }
  • 写回答

2条回答 默认 最新

  • ?Briella 2016-10-20 14:47
    关注

    Please try as bellow

    <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>
    

    In Ajax :

    Please add bellow code fro success

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

    PHP file for INSERT :

    Please add bellow code( Please correct if any misstates to retrieve data) after insert ($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>';
                 }
            }
        }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值