I'm trying to add ajax to my method laravel. This method is creating a reply under a discussion page. It was working before the Ajax, now i want to add the ajax to make the reply very fast ! i'm stack because i tried a lot of method to pass the $id (discussion_id) but no one works !
i'm using laravel 5.6
my route is :
Route::post('/discussion/reply/{id}', [
'uses' => 'DiscussionsController@reply',
'as' => 'discussion.reply'
]);
my function controller is :
public function reply($id)
{
$this->validate(request(), [
'reply' =>'required',
]);
$d = Discussion::find($id);
$reply = Reply::create([
'user_id' => Auth::id(),
'discussion_id' => $id,
'content' => request()->reply
]);
Session::flash('success', 'Votre réponse a été enregistrer avec success');
//return redirect()->back(); // this is what i was doing doing before the ajax
return response()->json(['success'=>'réponse ajouter']);
}
my JavaScript Ajax :
jQuery.ajax({
url: "/discussion/reply/",
method: 'post',
data: {
reply: jQuery('#reply').val(),
},
dataType: 'json',
success: function(data){
jQuery.each(data.errors, function(key, value){
jQuery('.alert-danger').show();
jQuery('.alert-danger').append('<p>'+value+'</p>');
});
}
});
and finally my form blade html :
<form action="{{ route('discussion.reply', ['id' => $d->id]) }}" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="reply">Laisser une réponse...</label>
<textarea name="reply" id="reply" cols="30" rows="10" class="form-control"></textarea>
</div>
<div class="form-group">
<button class="btn pull-right" id="submit">Répondre</button>
</div>
</form>