如何通过此ajax请求防止数据丢失


How to prevent data from being lost with this ajax request

我在博客文章的末尾有一个评论表单。到目前为止,在测试中,绝大多数情况下,评论都会成功保存到数据库中,但偶尔页面会给人一种成功发布评论的印象,但在重新加载页面后,评论就消失了(检查数据库表可以确认它从未成功发布过评论)。有没有办法在某个地方修改我的代码来捕捉这些反常事件?

我知道$.ajax有一个错误函数,但我认为在这个例子中添加它不会有帮助。实际的ajax请求似乎正在工作,因为它总是运行"success"函数中的内容。所以也许是postComment.php需要修改?

提交表单背后的代码:

if( $(".blogPost").length ) {
    $(".commentForm").submit(function(e) {
        e.preventDefault();
    }).validate({
            submitHandler: function (form) {
                var url = window.location.pathname;
                var post_url = url.substring(url.lastIndexOf('/') + 1);
                $("input[name=post_url]").val(post_url);
                var formData = $(form).serialize();
                var post_id = $(".post").attr("id");
                $.ajax({
                    url:"/postComment.php?PostID=" + post_id,
                    type:"POST",
                    data: formData,
                    success:function(data){
                        $(".comments").prepend(data);
                        $("#commentName").val("");
                        $("#commentEmail").val("");
                        $("#commentWebsite").val("");
                        $("#comment").val("");
                        $(".commentForm input[type='submit']").val('Success!').delay(5000).queue(function(){
                            $(".commentForm input[type='submit']").val('Post Comment');
                        });
                    }
                });
            }
        });
}

postComment.php页面上的代码:

<?php
include('dbconnect.php');
$name = $_POST['commentName'];
$email = $_POST['commentEmail'];
$website = $_POST['commentWebsite'];
if( $website != ''){
    if  ( $ret = parse_url($website) ) {
          if ( !isset($ret["scheme"]) )
           {
           $website = "http://{$website}";
           }
    }
}
$comment = $_POST['comment'];
$date = date('Y-m-d H:i:s');
$post_id = $_GET['PostID'];
$blogAuthor = '';
if( $name == "Luke Twomey"){
    $blogAuthor = "<span> - Blog Author</span>";
}else{
    $blogAuthor = false;
}
$SQL = "INSERT INTO comments (name, email, website, comment, date, post_id) VALUES ('$name', '$email', '$website', '$comment', '$date', '$post_id')";
mysqli_query($link, $SQL);
echo "<section class='comment'>
            <h3 class='commentAuthor'>$name$blogAuthor</h3>
            <a href='$website'><p class='commentAuthorWebsite'>$website</p></a>
            <p class='postDate'>$date</p>
            <p>$comment</p>
        </section>";
$subject = $name . $_POST['subject'];
$post_url = $_POST['post_url'];
$postedMessage = $_POST['comment'];
$contentForEmail = $postedMessage.'<br><a href="http://www.fakedomainhere.com/blog/'.$post_url.'#comments"><p>View comment on website</p></a>';
$header = "From: fake-email-here'n"
. "Reply-To: fake-email-here'n" . "Content-Type: text/html; charset=ISO-8859-1'r'n";
$email_to = "fake-email-here";
mail($email_to, $subject , $contentForEmail, $header );

?>

首先确保插入成功,然后只返回成功消息。

if(mysqli_query($link, $SQL)){
echo "<section class='comment'>
            <h3 class='commentAuthor'>$name$blogAuthor</h3>
            <a href='$website'><p class='commentAuthorWebsite'>$website</p></a>
            <p class='postDate'>$date</p>
            <p>$comment</p>
        </section>";
}else{
    echo "problem while inserting"; //or return an array with some status to tell the user to submit again.
// or header('HTTP/1.0 500 Internal Server Error'); exit;
    }

用以下内容确认插入没有问题:

$result = mysqli_query($link, $SQL);
if(!$result) {
    printf("Error: %s'n", mysqli_error($link));
} else {
    echo "<section ...

您可能应该了解如何正确地转义输入:http://php.net/manual/en/mysqli.real-escape-string.php

服务器端:

  • 检查SQL查询是否成功。

  • echotruefalse基于查询的成功或失败。

客户端:

$.ajax({
  url: "/postComment.php?PostID=" + post_id,
  type: "POST",
  data: formData,
  success:function(data){
    if(data == 'true') { // Prepend only If Successful
      $(".comments").prepend(data);
      $("#commentName").val("");
      $("#commentEmail").val("");
      $("#commentWebsite").val("");
      $("#comment").val("");
      $(".commentForm 
      input[type='submit']").val('Success!').delay(5000).queue(function() {
        $(".commentForm input[type='submit']").val('Post Comment');
      });
    } else { // Error
      alert("There was an issue in submitting your Comment. Please try again.");
    }
  }
});