This snippet demonstrates how to submit a form using an Ajax request in a Laravel application.
It provides a concise example of how to set up the form, handle the Ajax request, and process the response.

HTML Code
<form action="url" method="post" id="submitForm" enctype="multipart/form-data">
<!-- Inputs -->
<button type="button" id="submitButton">Submit</button>
</form>
<div id="loading" style="display: none;">Loading........</div>
Javascript Code
<script>
$(document).on("ready",function(){
$('#submitButton').on('click', function () {
let form = document.getElementById('submitForm');
let formData = new FormData(form);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.post({
url: '{{ route('url.route') }}',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
$('#loading').show();
},
success: function (data) {
if(data.errors){
for (let i = 0; i < data.errors.length; i++) {
toastr.error(data.errors[i].message, {
CloseButton: true,
ProgressBar: true
});
}
}
else{
toastr.success('Data Saved', {
CloseButton: true,
ProgressBar: true
});
setTimeout(function() {
location.href =
'{{ route('list.route') }}';
},800);
}
},
error: function (data) {
$.each(data.responseJSON.errors, function(key,value) {
toastr.error(value, {
CloseButton: true,
ProgressBar: true
});
});
},
complete: function () {
$('#loading').hide();
},
});
});
})
</script>
Laravel Controller
public function store () {
// Validate Inputs
$request->validate([
]);
// if Conditions
return response()->json(['errors' => [
['code' => 'default', 'message' => 'Error Messages']
]]);
// Success
return response()->json(['success'=>true]);
}