ajax——异步添加注释


ajax -- add comments asynchronously

我有两个php文件,用于处理我为网站创建的评论系统。在index.php上,我有一个表单和一个echo语句,它打印出数据库中的用户输入。我有另一个名为insert.php的文件,它实际上接收用户输入,并在打印出来之前将其插入到我的数据库中。

我的index.php基本上看起来像这个

<form id="comment_form" action="insertCSAir.php" method="GET">
    Comments:
    <input type="text" class="text_cmt" name="field1_name" id="field1_name"/>
    <input type="submit" name="submit" value="submit"/>
    <input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<!--connects to database and queries to print out on site-->
<?php
    $link = mysqli_connect('localhost', 'name', '', 'comment_schema');
    $query="SELECT COMMENTS FROM csAirComment";
    $results = mysqli_query($link,$query);
    while ($row = mysqli_fetch_assoc($results)) {
        echo '<div class="comment" >';
        $output= $row["COMMENTS"];
        //protects against cross site scripting
        echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
       echo '</div>';
    }
?>

我希望用户能够在不重新加载页面的情况下编写评论并进行更新(这就是我将使用AJAX的原因)。这是我添加到头标签的代码

<script     src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script>
        // this is the id of the form
        $("#comment_form").submit(function(e) {
        var url = "insert.php"; // the script where you handle the form input.
        $.ajax({
            type: "GET",
            url: url,
            data: $("#comment_form").serialize(), // serializes the form's elements.
            success: function(data)
            {
                alert(data); // show response from the php script.
            }
        });
        e.preventDefault(); // avoid to execute the actual submit of the form.
      });
   </script>

然而,什么都没有发生。alert()实际上并没有做任何事情,我也不知道如何制作它,这样当用户评论时,它会按顺序添加到我的评论中(它应该是在页面后面添加的)。我认为我添加的代码是需要发生的事情的基础,但即使是警报也不起作用。如有任何建议,我们将不胜感激。

这基本上是insert.php

if(!empty($_GET["field1_name"])) {
    //protects against SQL injection
    $field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
    $field1_name_array = explode(" ",$field1_name);
    foreach($field1_name_array as $element){
        $query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
        $query_link = mysqli_query($link,$query);
        if(mysqli_num_rows($query_link)>0){
            $row = mysqli_fetch_assoc($query_link);
            $goodWord = $row['replaceWord'];
            $element= $goodWord;
        }
        $newComment = $newComment." ".$element;
     }
     //Escape user inputs for security
     $sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
     $result = mysqli_query($link, $sql);
     //attempt insert query execution
     header("Location:index.php");
     die();
     mysqli_close($link);
}
else{
    die('comment is not set or not containing valid value');

它还过滤掉了不好的单词,这就是为什么有if语句检查的原因。

<?php
if(!empty($_GET["field1_name"])) {
//protects against SQL injection
    $field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
    $field1_name_array = explode(" ",$field1_name);
    foreach($field1_name_array as $element)
    {
        $query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
        $query_link = mysqli_query($link,$query);
        if(mysqli_num_rows($query_link)>0)
        {
            $row = mysqli_fetch_assoc($query_link);
            $goodWord = $row['replaceWord'];
            $element= $goodWord;
        }
        $newComment = $newComment." ".$element;
    }
//Escape user inputs for security
    $sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$newComment')";
    $result = mysqli_query($link, $sql);
//attempt insert query execution
    if ($result)
    {
        http_response_code(200); //OK
        //you may want to send it in json-format. its up to you
        $json = [
            'commment' => $newComment
        ];
        print_r( json_encode($json) );
        exit();
    }

//header("Location:chess.php");   don't know why you would do that in an ajax-accessed file
//die();
mysqli_close($link);
}
else{
    die('comment is not set or not containing valid value');
}

?>
<script>
        // this is the id of the form
        $("#comment_form").submit(function(e) {
        var url = "insert.php"; // the script where you handle the form input.
        $.ajax({
            type: "GET", //Id recommend "post"
            url: url,
            dataType: json,
            data: $("#comment_form").serialize(), // serializes the form's elements.
            success: function(data)
            {
                alert(data); // show response from the php script.
                $('#myElement').append( data.comment );
            }
        });
        e.preventDefault(); // avoid to execute the actual submit of the form.
      });
   </script>

要从"insert.php"获得响应,实际上需要从ajax请求打印/回显要在"success()"中处理的内容。

您还需要将响应代码设置为200,以确保将调用"success:function(data)"。否则,您可能会出现"error:function(data)"。