I want to add a comment system on my website using AJAX with Laravel to load new comments without refreshing whole page.
I always have this error :
Ajax Post 500 (Internal Server Error)
below is my code:
view page :
{!! Form::open(array('action' => array('PersonsController@newComment', $person->id))) !!}
<div class="form-group">
{!! Form::label('name', 'Nom ') !!}
{!! Form::text('name', null, ['class' =>'form-control', 'style'=>'border-radius: 0']) !!}
</div>
<div class="form-group">
{!! Form::label('mail', 'E-mail ') !!}
{!! Form::text('mail', null, ['class' =>'form-control', 'style'=>'border-radius: 0']) !!}
</div>
<div class="form-group">
{!! Form::label('comment', 'Contenu ') !!}
{!! Form::textarea('comment', null, ['class' =>'form-control', 'style'=>'border-radius: 0']) !!}
</div>
<div class="form-group">
{!! Form::submit('Publier', array('class'=>'send-btn')) !!}
</div>
{!! Form::close() !!}
route page :
Route::get('{id}/apropos','PersonsController@show');
Route::post('{id}/apropos','PersonsController@newComment');
Controller page :
public function newComment($id) {
if ($request::ajax()) {
$name = Input::get('name');
$mail = Input::get('mail');
$comment = Input::get('comment');
$Comments = new \App\Comment;
$Comments->Persons_id = $id;
$Comments->date = \Carbon\Carbon::now();
$Comments->name=$name;
$Comments->mail=$mail;
$Comments->comment=$comment;
$Comments->save();
$reponse =array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
} else {
return 'no';
}
}
Ajax page :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
$('.send-btn').click(function (e) {
e.preventDefault();
var name = $('#name').val();
var mail = $('#mail').val();
var comment = $('#comment').val();
$.ajax({
type: "POST",
url: '{{url("1/apropos")}}',
dataType: 'JSON',
data: {name: name, mail: mail, comment: comment},
success: function( data ) {
$("body").append("<div>"+data+"</div>");
}
});
});
});
I suppose that your ajax page is in the same page than the view (because you are using .send-btn).
It´s easier to use $.post() because you don´t need to configure so many parameters. https://api.jquery.com/jquery.post/
Do you have more information about the error: Ajax Post 500 (Internal Server Error). Don´t you have any message? Use error function on $.ajax:
error callback option is invoked, if the request fails. It receives the jqXHR, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport".
so you can add at your AJAX request something like:
error: function (xhr, textStatus, thrownError) {
console.log(xhr.status);
console.log(xhr.statusText);
console.log(textStatus);
console.log(thrownError);
}