Laravel | jQuery AJAX Template

<form id="form">
<!-- inputs -->
<button type="submit" id="submit">
submit
</button>
</form>
<script>
$('#submit').click(function(e){
e.preventDefault();
var form = new FormData(document.getElementById('form'))
$.ajax({
url: "/api/endpoint",
data: form,
type: 'post',
processData: false, // important
contentType: false, // important
cache: false,
success: function(data)
{
console.log(data)
// redirect
window.location.replace(data.redirect);
},
error: function(data)
{
// integrate Swal to display error
// you do your own error handling
Swal.close();
if (data.status == 419) {
window.location.reload();
} else {
Swal.fire({
icon: 'info',
title: 'Error',
html: data.responseJSON.message,
});
}
}
});
})
</script>
// laravel server side response examplereturn response()->json([
'message' => 'message ...',
'redirect' => 'https://example.com/path'
], 200);

--

--