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

Javascript 如何使用此ajax请求防止数据丢失,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我在博客文章的末尾有一个评论表。到目前为止,在测试过程中,绝大多数情况下,注释都成功地保存到数据库中,但是页面偶尔会给人留下成功发布注释的印象,但是在重新加载页面后,注释消失了(并且检查db表确认,它从来没有这么做过)。有没有办法修改我的代码来捕捉这些奇怪的事件 我知道$.ajax有一个错误函数,但我不认为在这个例子中添加它会有帮助。实际的ajax请求似乎正在工作——因为它总是运行“success”函数中的内容。那么,也许是postComment.php需要修改 提交表单后的代码: if( $(

我在博客文章的末尾有一个评论表。到目前为止,在测试过程中,绝大多数情况下,注释都成功地保存到数据库中,但是页面偶尔会给人留下成功发布注释的印象,但是在重新加载页面后,注释消失了(并且检查db表确认,它从来没有这么做过)。有没有办法修改我的代码来捕捉这些奇怪的事件

我知道$.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 );


?>

首先确保insert成功,然后只返回成功消息

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;
    }
if(mysqli_查询($link,$SQL)){
回声“
$name$blogAuthor

$comment

"; }否则{ 回显“插入时出现问题”;//或返回一个具有某种状态的数组,以通知用户再次提交。 //或标头(“HTTP/1.0 500内部服务器错误”);退出; }
确认插入物没有问题,如下所示:

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

if(!$result) {
    printf("Error: %s\n", mysqli_error($link));
} else {
    echo "<section ...
$result=mysqli\u查询($link,$SQL);
如果(!$result){
printf(“错误:%s\n”,mysqli_错误($link));
}否则{

echo“服务器端:

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

    }

  }

});
  • 检查SQL查询是否成功

  • 根据查询的成功或失败,回显truefalse

客户端:

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

    }

  }

});

ajax调用中没有错误处理程序,因此任何错误都将被忽略,但你是说当它不起作用时,你真的看到了“成功!”吗?如果是这样,那么问题就出在服务器上,因此可能需要一些日志记录来找出出了什么问题。正确-我看到了“成功!”!,并根据postComment.php:echo中的本节将注释添加到页面中"。你能详细说明一下或为我指出如何将日志添加到服务器的正确方向吗?我建议将一些调试信息直接转储到文本文件中,但下面的答案应该有助于了解是否存在问题,而不必走这条路。我通常在开始一个新项目时就有类似的内容,你几乎可以这样做保证您以后会需要它:p@Heru-抱歉,这是个错误的建议。最好是发送一个常规的200响应,响应数据中有一个指示错误的标志(可能还有错误消息本身).404和500错误的存在有一个特定的原因。你不应该假装它们发生在其他事情发生的时候。500肯定比404好,但当你可以简单地返回包含错误信息的数据对象时,你不应该强迫出错。谢谢。那么有没有办法强迫ajax请求失败?我在考虑用户-如果他们键入大量评论,然后发布-db insert失败,他们从postComment.php中看到“插入时出现问题”,但ajax请求仍然告诉他们这是成功的-他们输入的详细信息已从表单中清除。我可以让ajax请求失败-保留他们的评论不变,这样他们就可以尝试按“提交”了吗再次?@LukeTwomey添加
头('HTTP/1.0 404未找到');退出;
到else部分由于找到了页面,没有必要将其设为404。相反,您可以使用HTTP代码500(“内部服务器错误”)@Heru Luin则可以使用500内部服务器错误,但在不知道原因的情况下强制执行错误不是一个好的做法。谢谢,我会仔细阅读。我正赶着让这个网站开始运行,然后再回去正确学习PHP。这并不是我第一个承认的最佳做法!