Last active
August 21, 2023 01:46
-
-
Save davidwarrington/3a602864971ca97fdfc663f3b30b38d7 to your computer and use it in GitHub Desktop.
Submit a form with JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @param {HTMLFormElement} form */ | |
async function submitForm(form) { | |
const body = new FormData(body) | |
return fetch(form.action, { | |
method: form.method, | |
body, | |
}) | |
} | |
// Replace selector with whatever is suitable for your form | |
const form = document.querySelector('[data-submit-me-with-js-pls]') | |
form.addEventListener('submit', async event => { | |
event.preventDefault() | |
try { | |
await submitForm(form) | |
// Handle success | |
} catch (error) { | |
// Handle any errors | |
} finally { | |
// Optional. Clean up after yourself | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The function gets all the form data from your HTML, so if this script fails to load for any reason, your HTML should already be configured in a state where the form can submit successfully.
For example:
In Liquid you can use the
form
tag to generate a form