From b901dbd9aa1b10169642ac1b4652b4860fc6d64e Mon Sep 17 00:00:00 2001 From: Caen De Silva Date: Sat, 21 Oct 2023 13:55:21 +0200 Subject: [PATCH] Improve async form handler --- .../resources/dashboard.blade.php | 28 +++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/packages/realtime-compiler/resources/dashboard.blade.php b/packages/realtime-compiler/resources/dashboard.blade.php index 198533c7e91..8279abf7eac 100644 --- a/packages/realtime-compiler/resources/dashboard.blade.php +++ b/packages/realtime-compiler/resources/dashboard.blade.php @@ -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), @@ -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(); + } }); }