BEST_PRACTICES /
Ajax Form Submission

← Back

Overview

Sometimes it can be a good user-experience to submit forms via XHR/AJAX instead of causing a full page refresh.

Example

Here is a basic example, using delegated-events to handle form submission event capture. The same can be done using direct binding, e.g. form.addEventListener('submit').

on('submit', '.js-remote-form', async function (event) => {
  const form = event.currentTarget as HTMLFormElement
  event.preventDefault()
  let response
  try {
    // For get requests, use URLSearchParams instead:
    // const url = new URL(form.action, window.location.origin)
    // url.search = new URLSearchParams(new FormData(form))
    // response = await fetch(url.toString(), { method: form.method })
    response = await fetch(form.action, {
      method: form.method,
      body: new FormData(form)
    })
  } catch {
    // Ignore network errors
  }
  if (!response || !response.ok) {
    // Handle error state
  }
  // Handle success state
  // await response.json()
  // await response.text()
})