AJAX评论系统,ajax无法正常工作

时间:2017-05-29 23:15:53

标签: javascript php jquery html ajax

我正在为我正在制作的博客制作评论系统,目前我有两个问题。表格出现在每个帖子下面。但只适用于最高职位。其余表格根本不起作用。

我遇到的另一个问题是我正在使用ajax并且表单会将记录添加到SQL中,但我仍然需要刷新页面才能显示。我希望它在添加后立即自动显示。

tl:dr

两个问题:

  1. 唯一可行的形式是第一个帖子下的第一个,其余的根本不起作用

  2. Ajax不会自动显示注释,需要刷新才能看起来像

  3. 代码:

    JQuery的

    String

    的index.php

    function post()
    {
      var comment = document.getElementById("comment").value;
      var name = document.getElementById("name").value;
      var mail = document.getElementById("mail").value;
      var post_id = document.getElementById("post_id").value;
      if(comment && name && mail)
      {
        $.ajax
        ({
          type: 'post',
          url: 'php/comment.php',
          data:
          {
    
          user_comm:comment,
            user_name:name,
          user_mail:mail,
          post_id:post_id,
          },
          success: function (response)
          {
            document.getElementById("comments").innerHTML=response+document.getElementById("comments").innerHTML;
            document.getElementById("comment").value="";
          document.getElementById("name").value="";
          document.getElementById("mail").value="";
          }
        });
      }
    
      return false;
    }
    

    comment.php

    <div class="container">
    
            <div class="row">
                <div class="col-lg-8">
          <?php
               $result = mysql_query('SELECT * FROM `posts` ORDER BY id DESC') or die(mysql_error());
    
                  while($row = mysql_fetch_array($result)) {
                    $id_post = $row['id'];
                    $post_title = $row['post_title'];
                    $post_date = $row['date_created'];
                    $post_img = $row['post_img'];
                    $post_first = $row['post_first'];
                    $post_second = $row['post_second'];
    
    
    
                   echo " <!-- Blog Post Content Column -->
                        <h1> " . $row['post_title'] . " </h1><p class='lead'>
                        by <a href='#'>Matt</a></p>   <hr>
                         <p><span class='glyphicon glyphicon-time'>" . $row['date_created'] . "</span></p>
                         <img class='img-responsive' style='width: 900px;height: 300px;' src=" . $row['post_img'] . "> <hr>
                            <p class='lead'>" . $row['post_first'] . "</p>
                            <p>" . $row['post_second'] . "</p> <hr>";
    
    
              ?>
                            <!-- Comments Form -->
                        <div class='well'>
                                <h4>Leave a Comment:</h4>
                                <div class="new-com-cnt">
                                  <form method='post' onsubmit="return post();">
                                        <input type='hidden' id='post_id'name='post_id' value='<?php  echo $id_post; ?>'>
                                        <div class='form-group'>
                                          <input type="text" id="name" name="name-com" value="" placeholder="Your name" />
                                          <input type="text" id="mail" name="mail-com" value="" placeholder="Your e-mail adress" />
                                        <textarea type='text' id='comment' name='comment' class="form-control" rows='3'></textarea>
                                        </div>
                                       <input type="submit" value="Post Comment">
                                      </form>
                                  </div>
                            </div>
                            <hr>
    
     <?php
                   $resultcomments = mysql_query("SELECT * FROM `comment`  WHERE post_id = '$id_post' ORDER BY `date` DESC") or die(mysql_error());
                            while($affcom = mysql_fetch_assoc($resultcomments)){
                                $name = $affcom['name'];
                                $email = $affcom['mail'];
                                $comment = $affcom['comment'];
                                $date = $affcom['date'];
    
    
                                $default = "mm";
                                $size = 35;
                                $grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
    
                                ?>
    
                            <!-- Posted Comments -->
                            <div id='comments'class='media'>
    
                                  <a class='pull-left' href='#'>
                                      <img class='media-object' src=' <?php echo $grav_url; ?>' >
                                  </a>
                                  <div class='media-body'><?php echo $name; ?>
                                      <h4 class='media-heading'>
                                          <small><?php echo $date; ?></small>
                                      </h4>
                                        <?php echo $comment; ?>
                                  </div>
                              </div>
    
                          <?php
                        }
                      }
                      ?>
                </div>
    

    这是我第一次玩AJAX :)所以对我很轻松任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

您的父循环正在生成多个注释表单,并且它们都具有相同的ID。 Ids应该是整个文档的唯一。参考this。也许这导致其他评论表格除第一个之外不起作用。

你的第二个问题不是问题。这是服务器如何工作的一般行为。当您使用ajax时,它会将数据发送到服务器,并将其存储在数据库中。服务器的工作已经完成。它无法将数据发送回页面并在不刷新页面的情况下更新页面内容。您可以在发布到服务器后启动另一个ajax调用,以刷新页面内容。

虽然这与问题无关。尽量使用单引号和双引号。你不应该随机选择它们。决定一个并持续使用它们。是的,尝试学习PDO或mysqli。我会建议PDO。

答案 1 :(得分:0)

我测试了所有代码。它现在正在运作。我总体评论它,所以在代码中搜索“NB”(lat。为“Nota bene”),以便看到我做了相关更改。我将在这里描述一些问题,我也会给你一些建议 - 如果可以的话。最后,我将插入三个更正的页面。

问题:

  • 一个大问题是,您正在使用$id_post变量 SELECT sql语句(在comment.php中),它不存在 在comment.php代码中。
  • 其他问题:DOM元素具有相同的ID。里面的DOM元素 循环表单必须具有唯一的id属性。你必须永远拥有 html元素中的唯一id属性。给他们表格 例如id="<early-id><post_id>"
  • 在更多地方还有其他问题。我整体评论, 所以你必须阅读我的代码。

建议:

  • 使用mysqli_代替mysql_函数,因为mysql 扩展名已从PHP&gt; = 7.0完全删除。
  • 使用异常处理,尤其是在处理数据库访问时。
  • 不要从php内部编写HTML代码。如果你的话,用HTML替代php 希望,但不要做echo "<div class=...></div>"例如。这个 如果您使用可以格式化您的IDE,实际上非常重要 HTML代码。如果此代码在php中,则您没有机会这样做 美化过程。因此你可以错过重要的html标签 不知道它,因为你的IDE没有显示标签的位置 在页面中真的缺少。
  • 在html代码中:使用与name相同的id。示例:id=mail<?php echo $post_id; ?>name=mail<?php echo $post_id; ?>。例外:收音机 按钮,复选框和可以组成组的所有标签。然后,每个 tag会有一个唯一的id,但是所有这些都会收到相同的ID 名称
  • 在其中使用''整体和“”。保持这个“标准”,你会发现它比反向更好。

已更正页面:

的index.php:

<?php
try {
    $con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
    if (!$con) {
        throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
    }
    ?>

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
            <title>NB: TITLE</title>

            <!-- NB: Added my scripts for testing -->
            <link href="Vendor/Bootstrap-sass-3.3.7/Bootstrap.css" rel="stylesheet" type="text/css" />
            <script src="Vendor/jquery-3.1.0/jquery.min.js" type="text/javascript"></script>
            <script src="Vendor/Bootstrap-sass-3.3.7/assets/javascripts/bootstrap.min.js" type="text/javascript"></script>

            <script type="text/javascript" src="index.js"></script>
        </head>
        <body>
            <div class="container">
                <div class="row">
                    <div class="col-lg-8">
                        <?php
                        $result = mysqli_query($con, 'SELECT * FROM `posts` ORDER BY id DESC');
                        if (!$result) {
                            throw new Exception('The query could not be executed!');
                        }

                        while ($row = mysqli_fetch_array($result)) {
                            // NB: Unified $post_id name overall (instead of $id_post).
                            $post_id = $row['id'];
                            $post_title = $row['post_title'];
                            $post_date = $row['date_created'];
                            $post_img = $row['post_img'];
                            $post_first = $row['post_first'];
                            $post_second = $row['post_second'];
                            ?>

                            <!-- Blog Post Content Column -->
                            <!-- 
                                NB: Extracted html code from php and added here, where it should be.
                            -->
                            <h1>
                                <?php echo $post_title; ?>
                            </h1>
                            <p class="lead">
                                by <a href="#">Matt</a>
                            </p>
                            <hr/>
                            <p>
                                <span class="glyphicon glyphicon-time">
                                    <?php echo $post_date; ?>
                                </span>
                            </p>
                            <img class="img-responsive" style="width: 1200px; height: 100px;" src="<?php echo $post_img; ?>">
                            <hr/>
                            <p class="lead">
                                <?php echo $post_first; ?>
                            </p>
                            <p>
                                <?php echo $post_second; ?>
                            </p>
                            <hr/>

                            <!-- Comments Form -->
                            <div class="well">
                                <h4>Leave a Comment:</h4>
                                <div class="new-com-cnt">
                                    <form method="post" onsubmit="return post('<?php echo $post_id; ?>');">
                                        <!-- 
                                            NB: Deleted hidden input (not needed!) and was missing post_id in "id" attribute! 
                                                So: transfered post_id value to post() function as argument. See js too.
                                        -->
                                        <!-- 
                                            NB: Added post_id to the "id" attributes. See js too. 
                                        -->
                                        <div class="form-group">
                                            <input type="text" id="name<?php echo $post_id; ?>" name="name-com" value="" placeholder="Your name" />
                                            <input type="text" id="mail<?php echo $post_id; ?>" name="mail-com" value="" placeholder="Your e-mail adress" />
                                            <textarea type="text" id="comment<?php echo $post_id; ?>" name="comment" class="form-control" rows="3"></textarea>
                                        </div>
                                        <input type="submit" value="Post Comment">
                                    </form>
                                </div>
                            </div>

                            <hr>

                            <!-- 
                                NB: Added new "comments" outer-container in order to append 
                                    new comment to it and added post_id value into its "id" attribute.
                                    See the js too.
                            -->
                            <div id="comments<?php echo $post_id; ?>" class="comments-container">
                                <?php
                                $resultComments = mysqli_query($con, 'SELECT * FROM `comment`  WHERE post_id = ' . $post_id . ' ORDER BY `date` DESC');
                                if (!$resultComments) {
                                    throw new Exception('The query could not be executed!');
                                }

                                while ($affcom = mysqli_fetch_assoc($resultComments)) {
                                    $name = $affcom['name'];
                                    $email = $affcom['mail'];
                                    $comment = $affcom['comment'];
                                    $date = $affcom['date'];

                                    $default = "mm";
                                    $size = 35;
                                    $grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
                                    ?>

                                    <!-- Posted Comments -->
                                    <!-- 
                                        NB: deleted id attribute "comments", because I added an outer
                                        container to hold the insert results, e.g. the div 
                                        with the class "comments-container".
                                    -->
                                    <div class="media">
                                        <a class="pull-left" href="#">
                                            <img class="media-object" src="<?php echo $grav_url; ?>" >
                                        </a>
                                        <div class="media-body">
                                            <?php echo $name; ?>
                                            <h4 class="media-heading">
                                                <small><?php echo $date; ?></small>
                                            </h4>
                                            <?php echo $comment; ?>
                                        </div>
                                    </div>

                                    <?php
                                }
                                ?>
                            </div>
                            <?php
                        }
                        ?>
                    </div>
                </div>
            </div>
        </body>
    </html>
    <?php
    $closed = mysqli_close($con);
    if (!$closed) {
        throw new Exception('The database connection can not be closed!');
    }
} catch (Exception $exception) {
    // NB: Here you should just DISPLAY the error message.
    echo $exception->getMessage();

    // NB: And here you should LOG your whole $exception object.
    // NB: Never show the whole object to the user!
    // echo '<pre>' . print_r($exception, true) . '</pre>';

    exit();
}
?>

comment.php:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>NB: TITLE</title>
    </head>
    <body>
        <?php
        try {
            $con = mysqli_connect('<host>', '<user>', '<pass>', '<db>');
            if (!$con) {
                throw new Exception('Connect error: ' . mysqli_connect_errno() . ' - ' . mysqli_connect_error());
            }

            if (isset($_POST['user_comm']) && isset($_POST['user_name']) && isset($_POST['user_mail'])) {
                $comment = $_POST['user_comm'];
                $name = $_POST['user_name'];
                $mail = $_POST['user_mail'];
                $post_id = $_POST['post_id'];

                // NB: NEW. CHANGE THIS TO YOUR wished DATE FORMAT.
                // Use UNIX timestamps for dates, so that you make good date calculations.
                $date = date("Y-m-d");

                // NB: INSERT DATE IN DB TOO, so that you can select by date desc down under.
                $insert = mysqli_query($con, "INSERT INTO comment (name,mail,comment,post_id, date) VALUES ('$name', '$mail', '$comment', '$post_id', '$date')");
                if (!$insert) {
                    throw new Exception('The query could not be executed!');
                }

                // NB: Replaced $id_post with $post_id.
                $select = mysqli_query($con, "SELECT * FROM `comment`  WHERE post_id = '$post_id' ORDER BY `date` DESC");
                if (!$select) {
                    throw new Exception('The query could not be executed!');
                }

                if ($row = mysqli_fetch_array($select)) {
                    $name = $row['name'];
                    // NB: Added email, because it wasn't provided.
                    $email = $row['mail'];
                    $comment = $row['comment'];
                    $date = $row['date'];

                    // NB: It wasn't provided, so I added the same value as in index.php.
                    $default = "mm";
                    $size = 35;
                    $grav_url = "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . $default . "&s=" . $size;
                    ?>
                    <div class="media">
                        <a class='pull-left' href='#'>
                            <!-- 
                                NB: Where is your $grav_url value?! I added one of mine for testing.
                            -->
                            <img class='media-object' src=' <?php echo $grav_url; ?>' >
                        </a>
                        <div class='media-body'>
                            <?php echo $name; ?>
                            <h4 class='media-heading'>
                                <small><?php echo $date; ?></small>
                            </h4>
                            <?php echo $comment; ?>
                        </div>
                    </div>
                    <?php
                }

                // NB: Don't use exit(). Let the code flow further, because 
                // you maybe want to close the db connection!
                // exit();
            }

            $closed = mysqli_close($con);
            if (!$closed) {
                throw new Exception('The database connection can not be closed!');
            }
        } catch (Exception $exception) {
            // NB: Here you should just DISPLAY the error message.
            echo $exception->getMessage();

            // NB: And here you should LOG your whole $exception object.
            // NB: Never show the whole object to the user!
            // echo '<pre>' . print_r($exception, true) . '</pre>';

            exit();
        }
        ?>
    </body>
</html>

Javascript文件:

// NB: Added post_id as parameter. See form too.
function post(post_id) {
    // NB: Added post_id value to the "id" attributes. See form too.
    var comment = document.getElementById("comment" + post_id).value;
    var name = document.getElementById("name" + post_id).value;
    var mail = document.getElementById("mail" + post_id).value;

    if (comment && name && mail) {
        $.ajax({
            type: 'post',
            url: 'php/comment.php',
            data: {
                user_comm: comment,
                user_name: name,
                user_mail: mail,
                post_id: post_id
            },
            success: function (response) {
                // NB: Comments-post_id is now an outer container. See form.
                // NB: Added post_id value to the "id" attributes. See form too.
                document.getElementById("comments" + post_id).innerHTML = response + document.getElementById("comments" + post_id).innerHTML;
                document.getElementById("comment" + post_id).value = "";
                document.getElementById("name" + post_id).value = "";
                document.getElementById("mail" + post_id).value = "";
            }
        });
    }

    return false;
}


// ******************************************************************************
// NB: Recommendation:
// ******************************************************************************
// Use jquery and ajax instead of vanilla javascript. It's no problem anymore ;-)
// Use done, fail, always instead of success, error, ....
// ******************************************************************************
//function post(post_id) {
//    var comment = $('#comment' + post_id);
//    var name = $('#name' + post_id);
//    var mail = $('#mail' + post_id);
//
//    if (comment && name && mail) {
//        var ajax = $.ajax({
//            method: 'POST',
//            dataType: 'html',
//            url: 'php/comment.php',
//            data: {
//                user_comm: comment.val(),
//                user_name: name.val(),
//                user_mail: mail.val(),
//                post_id: post_id
//            }
//        });
//        ajax.done(function (data, textStatus, jqXHR) {
//            var comments = $("#comments" + post_id);
//            
//            // NB: I'm not sure, not tested, too tired :-) Please recherche.
//            comments.html(data + comments.html());
//            
//            comment.val('');
//            name.val('');
//            mail.val('');
//        });
//        ajax.fail(function (jqXHR, textStatus, errorThrown) {
//            // Show error in a customized messages div, for example.
//            $('#flashMessage').val(textStatus + '<br />' + errorThrown);
//        });
//        ajax.always(function (data, textStatus, jqXHR) {
//            //...
//        });
//    }
//
//    return false;
//}
// ******************************************************************************
祝你好运。