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\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 );
?>