ajax - 异步添加注释

时间:2016-03-23 20:03:51

标签: javascript php jquery ajax

我有两个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的原因)。这是我添加到head标签的代码

<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语句检查的原因。

1 个答案:

答案 0 :(得分:0)

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

从&#34; insert.php&#34;获得回复你实际上需要在&#34; success()&#34;中打印/回显你想要处理的内容。来自ajax-request。

此外,您还要将响应代码设置为200,以确保&#34;成功:功能(数据)&#34;将被召唤。否则,您最终可能会出现错误:函数(数据)&#34;。