Why do I get error 422 when I send the form to Laravel with Ajax?
my ajax code :
document.getElementById('addReplyComment').addEventListener('submit',()=> {
$.ajax({
type: 'POST',
url: "{{ route('comments.reply')}}",
data: $('#addReplyComment').serialize(),
success: function (response) {
alert(response)
},
error: function (error) {
console.log(error)
}
});
}
controller code :
public function showCommentModal(Request $request){
if(\request()->ajax()){
$data = $request->validate([
'commentable_id' => 'required',
'commentable_type' => 'required',
'parent_id' => 'required',
]);
return view('layouts.modalReplyComment',compact('data'));
}
return response('just ajax request');
}
form:
<form action="javascript:void(0)" id="addReplyComment">
@csrf
<input type="hidden" name="commentable_id" value="{{ $product->id }}">
<input type="hidden" name="commentable_type" value="{{ get_class($product) }}">
<input type="hidden" name="parent_id" value="{{$comment->id}}">
<button type="submit"data-toggle="modal"data-id="{{$parentComment->id}}"title="reply">
<img src="{{asset('images/reply.png')}}" alt="reply" height="20px"width="20px">
</button>
</form>
The request is empty when I get dd($request).