I want to make an ajax call and try to show validation messages on front end. I use a modal to make ajax call, but I can't use normal @error('name') @enderror
directive so I use jQuery validator plugin, but errors occur.
I tried different things, but did not find a solution yet. Please help me.
Ajax call with validate plugin
<script>
$(document).ready(function() {
$('#create-collection-form').validate({
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
});
$('#create-collection').click(function(event) {
event.preventDefault();
$.ajax({
url: '{{ route('collections.store') }}',
type: 'POST',
dataType: 'json',
data: $('#create-collection-form').serialize(),
success: function (data) {
$('#create-collection-form').trigger('reset');
$('#createCollectionModal').modal('hide');
$('.collections').append('<li> ' + data.name + ' </li>');
}
});
});
});
</script>
Store method in my controller with back-end validation data
public function store(Request $request)
{
$attributes = $request->validate([
'name' => 'required|min:3',
'description' => 'nullable|min:3'
]);
$collection = Collection::create($attributes);
return Response::json($collection);
}
Errors:
jQuery plugin version is 3.4.1 (latest) and validator is 1.19.0, jQuery is first followed by validator plugin so I dont think that order is the problem here. Please help me, I'm stuck with this so hard! I am a beginner, and I am trying to learn ajax to make my life easier, but it seems it otherwise :)).
Why I cant use the @error directive, it will be easier.