最近滿常要把一般 form-submit 改成 AJAX 非同步去送表單,所以分享個 template。
非 Laravel 做的後端也適用
<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)
{
// intergrate Swal to display error
Swal.close();
if (data.status == 419) {
window.location.reload();
} else {
Swal.fire({
icon: 'info',
title: 'Error',
html: data.responseJSON.message,
});
}
}
});
})
</script>
Laravel Response 範例
return response()->json([
'message' => 'message ...',
'redirect' => 'https://example.com/path'
], 200);