Skip to content

Instantly share code, notes, and snippets.

@davidwarrington
Last active August 21, 2023 01:46
Show Gist options
  • Save davidwarrington/3a602864971ca97fdfc663f3b30b38d7 to your computer and use it in GitHub Desktop.
Save davidwarrington/3a602864971ca97fdfc663f3b30b38d7 to your computer and use it in GitHub Desktop.
Submit a form with JS
/** @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
}
})
@davidwarrington
Copy link
Author

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:

<form action="/my-endpoint">
  <label for="message">
    Message
  </message>

  <button type="submit">
    Go on then, submit me
  </button>
</form>

In Liquid you can use the form tag to generate a form

{% form 'contact' %}
  <button type="submit">
    Submit
  </button>
{% endform %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment