Reputation: 173
I created this page https://musikversicherung.com/anfrage/ and I can't figure out why the fetch request when submitting the form fails in firefox (v80.0.1, no addons). It works fine in Chrome, Safari, and Edge and posts the formData to formbackend. What surprises me is that in firefox nothing gets logged to the console but the user gets redirected to "/fehler/". So I don't really now how to debug this. I have tried different request headers but nothing has worked so far. Here is the github repo: https://github.com/jannispaul/musikversicherung-eleventy and below you can find the slightly simplified code.
var requestOptions = {
method: "POST",
body: new FormData(event.target),
redirect: "follow",
};
let requestUrl = "formbackend.com/mylink";
fetch(requestUrl, requestOptions)
.then((response) => {
// If response is ok
if (response.ok) {
console.log("fetch response ok");
// redirect to schaden-gemeldet page
window.location.href = redirectUrl;
// Clear saved formdata from localstorage
localStorage.removeItem(storageID);
}
})
// If there is an error log it to console and reidrect to fehler page
.catch((error) => {
console.error("Error: ", error);
window.location.href = "/fehler/";
});
I would greatly appreciate if someone could explain to me what I am doing wrong. Thanks!
Upvotes: 0
Views: 1458
Reputation: 173
To answer my own question as it may be helpful for someone in the future:
The code referenced in the question was not the problem. The issue was that Firefox blocked the fetch request as the page was reloading after the submit-button had been clicked.
e.preventDefault()
did not prevent the page from loading as the event bubbled. The solution was to set cancelable to true: https://developer.mozilla.org/en-US/docs/Web/API/Event/cancelable
Here is the code:
document
.querySelector("form")
.dispatchEvent(
new Event("submit", { bubbles: true, cancelable: true })
);
Upvotes: 1