如何使用此ajax请求防止数据丢失

I have a comment form at the end of my blog posts. In testing so far the vast majority of times the comments are successfully saved into the database, however very occasionally the page gives the impression of having posted the comment successfully - but after reloading the page the comment has disappeared (and checking the db table confirms it never made it that far). Is there a way of amending my code somewhere to catch these freak occurrences?

I am aware that $.ajax has an error function, but I don't think adding that in this instance will help. The actual ajax request seems to be working - because it always runs what is in the 'success' function. So perhaps it's postComment.php that needs the amendment?

Code behind the form submit:

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');
                        });
                    }
                });
            }
        });

}

Code on postComment.php page:

<?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
"
. "Reply-To: fake-email-here
" . "Content-Type: text/html; charset=ISO-8859-1
";

$email_to = "fake-email-here";

mail($email_to, $subject , $contentForEmail, $header );


?>

First make sure that insert is success then only return the success message.

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;
    }

Confirm that there's nothing wrong with the insert with something like this:

$result = mysqli_query($link, $SQL);

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

And you should probably read up on how to properly escape the input: http://php.net/manual/en/mysqli.real-escape-string.php

Server Side:

  • Check if SQL Query was Successful.

  • echo true or false based on your Query's Success or Failure.

Client Side:

$.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.");

    }

  }

});