SELECT after INSERT with AJAX

时间:2016-10-20 13:20:25

标签: php jquery mysql ajax select

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 个答案:

答案 0 :(得分:1)

请尝试以下

<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);
    },

INSERT的PHP文件:

请在插入后添加以下代码(请更正,如果有任何错误检索数据)($ comment_stmt-&gt; 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>';
             }
        }
    }

答案 1 :(得分:0)

在评论表单页面中:删除select查询系统。您只需添加div <div class="comment-result"></div>。如果Ajax请求成功,则append comment-result

中的数据为div
<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>

<div class="comment-result">

</div>

INSERT和SELECT的PHP文件。我在Select评论后添加了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();

    //select all comment list
    $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和SELECT的AJAX(我添加了新行$('.comment-result').prepend(data);

success: function (data) {
    if (data == "Error!") {
        alert("Unable to post comment!");
        alert(data);
    } else {
        $("#comment-form")[0].reset();
        $('.comment-result').append(data); //added new line
    }
}