当有多个表单时,Ajax评论系统不能正常工作


Ajax comment System not working properly when having multiple forms

所以我做这个网站的类,我需要使用ajax的评论系统。到目前为止,我设法用户JavaScript和什么不保存到数据库,但当我按下提交它不显示评论。

另一个问题是,当我说2个帖子,它会生成2个表单。1个表单不能与ajax一起工作,甚至不能插入数据库。

<<p> index . php代码/strong>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script  src="comments.js"></script>
    <?php 
        require_once("menu.php");
        $connection = connectToMySQL();

        $selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
        $result = mysqli_query($connection,$selectPostQuery)
            or die("Error in the query: ". mysqli_error($connection));
        while ($row = mysqli_fetch_assoc($result)) 
        {
            $postid = $row['ID'];
    ?>
            <div class="wrapper">
            <div class="titlecontainer">
            <h1><?php echo $row['Title']?></h1>
            </div>
            <div class="textcontainer">
            <?php echo $row['Content']?>
            </div>
    <?php
            if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
            {
    ?>
                <div class="imagecontainer">
                <img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
                </div>
    <?php
            }
    ?>
            <div class="timestampcontainer">
            <b>Date posted :</b><?php echo $row['TimeStamp']?>
            <b>Author :</b> Admin
            </div>
    <?php
            #Selecting comments corresponding to the post
            $selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
            $commentResult = mysqli_query($connection,$selectCommentQuery)
                or die ("Error in the query: ". mysqli_error($connection));
            #renderinf the comments
            while ($commentRow = mysqli_fetch_assoc($commentResult)) 
            {
    ?>
                <div class="commentcontainer">
                <div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
                <div class="commentcontent"><?php echo $commentRow['Content']?></div>
                <div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
                </div>
    <?php
            }

            if (!empty($_SESSION['userID']) ) 
            {
    ?>
                <form method="POST" class="post-frm" id="form">
                <label>New Comment</label>
                <textarea id="comment" name="comment"> </textarea>
                <input type="hidden" name="postid" value="<?php echo $postid ?>">
                <input id="submit" type="submit" name ="submit" class="button"/>
                </form>
    <?php
            }
            echo "</div>";
            echo "<br /> <br /><br />"; 
        }
     require_once("footer.php") ?>
     $(document).ready(function(){
        var form = $('#form');
        var submit = $('#submit');
        form.on('submit',function(e) {
            e.preventDefault();
            //send ajax request
            $.ajax({
                url: 'ajax_comment.php',
                type: 'POST',
                cache: false,
                data: form.serialize(), //form serialize data
                beforeSend: function(){
                    //Changeing submit button value text and disableing it
                    submit.val('Submiting ....').attr('disabled', 'disabled');
                },
                success: function(data)
                {
                    var item = $(data).hide().fadeIn(800);
                    $('.comment-block').append(item);
                    // reset form and button
                    form.trigger('reset');
                    submit.val('Submit').removeAttr('disabled');
                },
                error: function(e)
                {
                    alert(e);
                }
            });
        });
    });

AJAX PHP页面

    <?php
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
        session_start();
        include('connection.php');
        $connection = connectToMySQL();
            $userId = $_SESSION['userID'];
            $postId = $_POST['postid'];
            $comment = $_POST['comment'];
            $insertCommentQuery = "INSERT INTO `tblcomments`       (`Content`,`UserID`,`PostID`,`Timestamp`) VALUES ('$comment','$userId','$postId',CURRENT_TIMESTAMP)";
            $result = mysqli_query($connection,$insertCommentQuery);

    ?>
     <div class="commentcontainer">
     <div class="commentusername"><h1>Username :This is atest</h1></div>
     <div class="commentcontent">This is a test</div>
     <div class="commenttimestamp">Test</div>
     </div>
   <?php
    connectToMySQL(0);
   endif?>

更改您的index.php

...
  #renderinf the comments
   echo '<div class="comment-block_' . $postid .'">';
        while ($commentRow = mysqli_fetch_assoc($commentResult)) 
        {
?>
            <div class="commentcontainer">
            <div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
            <div class="commentcontent"><?php echo $commentRow['Content']?></div>
            <div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
            </div>
<?php
        }
  echo '</div>';
...

AJAX PHP页面更改

 <?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])):
    session_start();
    include('connection.php');
    $connection = connectToMySQL();
        $userId = $_SESSION['userID'];
        $postId = $_POST['postid'];
        $comment = $_POST['comment'];
        $insertCommentQuery = "INSERT INTO `tblcomments` 
                               (`Content`,`UserID`,`PostID`,`Timestamp`) 
                              VALUES (
                                 '$comment','$userId','$postId',
                                  CURRENT_TIMESTAMP)";
        $result = mysqli_query($connection,$insertCommentQuery);

$obj = array();
$obj['id'] = $postId;
$obj['html'] = '<div class="commentcontainer">
                    <div class="commentusername"><h1>Username :This is atest</h1></div>
                    <div class="commentcontent">This is a test</div>
                    <div class="commenttimestamp">Test</div>
               </div>';
echo json_encode($obj);
    connectToMySQL(0);
   endif?>

和你的AJAX

 $(document).ready(function(){
   $('#submit').on('click',function(e) {
        e.preventDefault();
        //send ajax request
        var form = $(this).closest('form');
        $.ajax({
            url: 'ajax_comment.php',
            type: 'POST',
            cache: false,
            dataType: 'json',
            data: $(form).serialize(), //form serialize data
            beforeSend: function(){
                //Changeing submit button value text and disableing it
                $(this).val('Submiting ....').attr('disabled', 'disabled');
            },
            success: function(data)
            {
                var item = $(data.html).hide().fadeIn(800);
                $('.comment-block_' + data.id).append(item);
                // reset form and button
                $(form).trigger('reset');
                $(this).val('Submit').removeAttr('disabled');
            },
            error: function(e)
            {
                alert(e);
            }
        });
    });
});