I'm implementing the comments system on my PHP platform that is based on Laravel 4.
The problem at the moment is that when I send a new comment it gets saved into the database but then the comments list returned doesn't contain the just inserted comment.
So, bottom up, this is the path the comment "follows" before reaching the database:
This function just pass the comment's data to another function, manage some UI elements and then retrieve a list of all the comments if everything is OK:
$("#comments-button-new").click(function() {
var parameters = url.getURLParameters();
var entryID = parameters.pop(); // Put this inside a data attribute
comments.sendComment(
$("#comments-input-comment-new").val(),
entryID,
$("#comments-token").val(),
function() {
$("#comments-alert-error").addClass('hidden');
$("#comments-button-new").html("<span class='glyphicon glyphicon-ok'></span>");
getComments(); // When the POST response is received comments are retrieved
},
function() {
$("#comments-alert-error").removeClass('hidden');
}
);
});
This is the function that actually make the POST request to the server:
function sendComment(content, entryID, token, doneCallback, failCallback) {
$.post("http://localhost/comment/new",
{
content : content,
entryID : entryID,
_token : token
})
.done(doneCallback())
.fail(function(xhr) {
failCallback(xhr.response);
});
}
This is the controller that handles the comment:
public function newComment() {
$content = Input::get('content');
$entryID = Input::get('entryID');
$hashids = new \Hashids\Hashids(Config::get('security.salt'), Config::get('security.minimumHashLength'));
$entryID = $hashids->decrypt($entryID);
$comment = new Comment();
$result = $comment->newComment($content, $entryID[0]);
if($result != 'OK') {
return Response::make($result, 500);
}
return Response::make('OK', 200);
}
And this is the newComment
function located in the Comment
model that saves the comment in the DB:
public function newComment($content, $entryID) {
$validator = Validator::make(
array(
'content' => $content,
'entryID' => $entryID
),
array(
'content' => 'max:'.self::$COMMENT_MAX_LENGTH,
'entryID' => 'exists:entries,id'
)
);
if($validator->fails()) {
return $validator->messages()->all();
}
$this->author = Auth::user()->username;
$this->content = $content;
$this->parentEntryID = $entryID;
$this->save(); // Comment is saved in the Database
return 'OK';
}
The comment is correctly saved in the database, then, following the returns you can see that after that I want to retrieve all entry's comments. Problem is that all the comments but one are returned. If I try to reload the page than every comment, including the last one, is returned.
It looks like that the getComments
JS function is executed before the comment is saved in the DB.
Edit:
Not sure if relevant or not but the JS functions make use of require.js.