I'm working on a blog commenting feature on a website but I am having some challenges getting the commenting ajax request feature to work.
Here's my code below
Form
{!! Form::open(['id' => 'comment_form']) !!}
<div>
{!! Form::hidden('article_id', $article->id) !!}
</div>
<div>
{!! Form::hidden('user_id', 1) !!}
{!! Form::hidden('username','name') !!}
{!! Form::hidden('email','fname.lname@mail.com') !!}
{!! Form::hidden('password','**__**') !!}
{!! Form::hidden('service_id', 1) !!}
</div>
<div class="form-group">
{!! Form::textarea('comment', null, ['class' => 'form-control', 'placeholder' => "Keep your comments to less than 250 chars"]) !!}
</div>
<div class="form-group">
{!! Form::submit('Post!',['class' => 'btn btn-primary form-control', 'id' => 'comment' ]) !!}
</div>
{!! Form::close() !!}
Then below is my Ajax request using jQuery
$('#comment_form').on('submit', function(e) {
$.ajaxSetup({
header:$('meta[name="_token"]').attr('content')
});
e.preventDefault(e);
$.ajax({
type: "POST",
url: '/articles/comment',
data: $(this).serialize(),
dataType:'json',
delay: 2000,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("Failure");
}
});
});
And the Receiving Controller snippet is shown below
public function enterComment(Request $request)
{
// First check that the commenter is logged in with the session controller
// If not force the person to be logged in
$this->validate($request, ['comment' => 'required','user_id' => 'required']);
try{
// I am supposed to use the user_id record which is in the session.
// However since I don't have my session variable created and model working
// I will use this
$user = User::where('user_id',$request['user_id'])->firstOrFail();
}
catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
// Ask user to to register his details.
// For action tomorrow
$user = User::create(['username'=> $request['username'],'email' => $request['email'],'password' => $request['password'],'service_id' => $request['service_id']]);
}
// Register comment
$comment = new Comment;
$comment->comment = $request['comment'];
$comment->article_id = $request['article_id'];
$comment->user_id = $request['user_id'];
$comment->published_at = Carbon::now();
$comment->save();
dd($comment,$user);
return response()->json(['comment' => $comment->comment], 200);
}
That's what I am troubleshooting now and unfortunately I have not been able to figure out what I am doing wrong. Please can anyone help me out with this.