Skip to content
FormToMail

HTML form to email

How do I submit a form with fetch() and show a thank-you message without reloading?

By the FormToMail team · Checked against official sources · Updated

Listen for the form's submit event, call e.preventDefault(), send `new FormData(form)` with `fetch()` and the header `Accept: application/json`, then show a thank-you message from the JSON answer. The page never reloads and the visitor stays where they were.

Request formats a form endpoint accepts
BodyContent-TypeNotes
new FormData(form)multipart/form-data (set by the browser)Easiest; don't set Content-Type yourself
new URLSearchParams(new FormData(form))application/x-www-form-urlencodedA "simple" request: no CORS preflight
JSON.stringify({...})application/jsonTriggers a CORS preflight; the endpoint must answer OPTIONS

Full example

html
<form id="contact">
  <input name="email" type="email" required>
  <textarea name="message" required></textarea>
  <button>Send</button>
  <p id="status" role="status"></p>
</form>
<script>
  const form = document.getElementById("contact");
  form.addEventListener("submit", async (e) => {
    e.preventDefault();
    const status = document.getElementById("status");
    status.textContent = "Sending…";
    const res = await fetch("https://getformtomail.com/f/YOUR_FORM_ID", {
      method: "POST",
      body: new FormData(form),
      headers: { Accept: "application/json" },
    });
    const data = await res.json();
    status.textContent = data.ok ? "Thanks! We'll reply soon." : data.error;
    if (data.ok) form.reset();
  });
</script>

Common mistakes

  • Setting Content-Type: multipart/form-data manually: the browser must add the boundary itself.
  • Forgetting Accept: application/json, so you get a redirect instead of JSON.
  • No error branch: show data.error so people know when something failed.

Quick answers

Do form backends work with AJAX and JSON?

FormToMail does: it answers JSON when you send Accept: application/json or a JSON body, with CORS open to any origin.

How do I use a form backend with alpine.js?

Same fetch() call inside an @submit.prevent handler.

How do I track form submissions in Google Analytics?

Fire your analytics event in the data.ok branch, so only successful sends are counted.

How do I add a hidden field to track which page the form came from?

Add <input type="hidden" name="page"> and set it to location.pathname before sending. FormToMail also records the referring page.

What to do next

Grab an endpoint and drop it into the fetch() call above.

Get your form endpoint

Sources

Checked: . Prices, limits and features of other services change: confirm current values at the official links above. Product names belong to their owners; we are not affiliated with them.