There are several questions like this on SO but none of the answers have worked for me. I have tried them all.
I tried to minimize the code I am pasting, but it's kind of hard with this script
I have a comment form that is submitted via ajax to a php script which saves the comment and then gets all the comments and redisplays them so the new comment can be displayed without refreshing the page.
Only sometimes will the comments successfully submit to the database and redisplay properly. Usually almost every other submit the comment will be saved. Every other time nothing seems to happen.
My real issue is the comments not being saved every time one is submitted.
Here is the javascript and the ajax call:
$(document).ready(function(){
var working = false;
$('#commentForm').submit(function(e){
if(working) return false;
working = true;
$('#submitComment').val('Working..');
$('span.error').remove();
$.post('/ajax/comment.process.php',$(this).serialize(),function(msg){
working = false;
$('#submitComment').val('Submit');
if(msg.status){
$('#commentArea').slideDown().$(msg.html).prepend('#commentArea');
$('#blogComment').val('');
}
else {
$.each(msg.errors,function(k,v){
$('label[for='+k+']').append('<span class="error">'+v+'</span>');
});
}
},'json');
});
});
and here is the function that submits the comment:
public function addComment($user_id) {
$validate = new data_validation;
$_POST = $validate->sanitize($_POST);
$newCom = $_POST['blogComment'];
$blog_id = intval($_POST['blogID']);
$photoSubmit = $_POST['comPhoto'];
$newComQuery = $this->mysqli->query("INSERT INTO b_comments (blog_id, user_id, date, content, photo) VALUES ('".$blog_id."', '".$user_id."', Now(), '".$newCom."', '".$photoSubmit."')");
if($newComQuery === false) {
echo "Query failed";
}else{
$returnCom = $this->comMarkup($blog_id);
echo $returnCom;
}
}
and here is a piece of the comMarkup()
function that echos the comments (it is only the important pieces):
// This method outputs the XHTML markup of the comment
public function comMarkup($blog_id) {
$sql = $this->mysqli->query("SELECT * FROM b_comments WHERE blog_id = '".$blog_id."' ORDER BY date DESC");
while($d = $sql->fetch_assoc()) {
$d = $validate->sanitize($d);
echo "
<div class='comment-block'>
<span class='com-img'><img src='".$photo_path."' /></span>
<h3 style='display: inline;'><a href='".$profile."'>".$userName."</a></h3>
<div class='com-date'>".$d['date']."</div>
<p>".$comContent."</p>
</div>
";
}
}
EDIT: Here is the comment.process.php code as requested:
session_start();
include_once('../classes/comment.class.php');
include_once('../classes/db.class.php');
include_once('../classes/user.class.php');
$user_id = $_SESSION['user_id'];
$db = new DBConnection;
$comments = new Comment($db);
$user = new User($db);
$blogID = intval($_POST['blogID']);
$addCom = $comments->addComment($user_id);
echo json_encode(array('status'=>1,'html'=>$addCom));