Skip to content

Commit

Permalink
Improve async form handler
Browse files Browse the repository at this point in the history
  • Loading branch information
caendesilva committed Oct 21, 2023
1 parent b9d4f41 commit b901dbd
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions packages/realtime-compiler/resources/dashboard.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,13 +280,22 @@
/**
* Progressive enhancement when JavaScript is enabled to intercept form requests
* and instead handle them with an asynchronous Fetch instead of refreshing the page.
*
* @param {Element} form
* @param {?callback} okHandler
* @param {?callback} errorHandler
* @param {?callback} beforeCallHandler
* @param {?callback} afterCallHandler
*/
function registerAsyncForm(form) {
function registerAsyncForm(form, okHandler = null, errorHandler = null, beforeCallHandler = null, afterCallHandler = null) {
form.addEventListener("submit", function (event) {
// Disable default form submit
event.preventDefault();
if (beforeCallHandler) {
beforeCallHandler();
}
fetch("", {
method: "POST",
body: new FormData(event.target),
Expand All @@ -295,15 +304,24 @@ function registerAsyncForm(form) {
}),
}).then(response => {
if (response.ok) {
// Request was successful, no need to do anything.
if (okHandler) {
okHandler(response);
}
} else {
// Request failed, let's log it.
console.error("Fetch request failed.");
if (errorHandler) {
errorHandler(response);
} else {
console.error("Fetch request failed.");
}
}
}).catch(error => {
// Handle any network-related errors
console.error("Network error:", error);
});
if (afterCallHandler) {
afterCallHandler();
}
});
}
Expand Down

0 comments on commit b901dbd

Please sign in to comment.