Form ID

Plain JavaScript

Progressively enhance an HTML form with fetch: inline field errors, a status message and no page reload.

This page needs no build step and no package. The form works as a normal HTML post when JavaScript is off; with it on, the script posts with fetch and shows the result inline.

contact.html
<form id="contact" action="https://ikiform.com/f/frm_xxxxxxxxxxxxxxxx" method="post" novalidate>
  <label for="email">Email</label>
  <input id="email" name="email" type="email" required aria-describedby="email-error" />
  <p id="email-error" data-error-for="email"></p>
  <label for="message">Message</label>
  <textarea id="message" name="message"></textarea>
  <p id="message-error" data-error-for="message"></p>
  <input name="_gotcha" type="text" tabindex="-1" autocomplete="off" hidden />
  <button>Send</button>
  <p role="status" data-status></p>
</form>

<script type="module">
  const form = document.querySelector("#contact");
  const button = form.querySelector("button");
  const status = form.querySelector("[data-status]");

  function showErrors(fields = {}) {
    for (const slot of form.querySelectorAll("[data-error-for]")) {
      const messages = fields[slot.dataset.errorFor];
      slot.textContent = messages ? messages[0] : "";
      form.elements[slot.dataset.errorFor]?.setAttribute("aria-invalid", messages ? "true" : "false");
    }
  }

  form.addEventListener("submit", async (event) => {
    event.preventDefault();
    button.disabled = true;
    status.textContent = "Sending";
    try {
      const response = await fetch(form.action, {
        method: "POST",
        headers: { Accept: "application/json" },
        body: new FormData(form),
      });
      const result = await response.json();
      showErrors(result.ok ? {} : result.error.fields);
      status.textContent = result.ok ? "Thanks, we got it." : result.error.message;
      if (result.ok) form.reset();
    } catch {
      status.textContent = "Couldn't reach the server. Check your connection and try again.";
    } finally {
      button.disabled = false;
    }
  });
</script>
  • Accept: application/json makes Ikiform answer with JSON instead of a redirect.
  • result.error.fields is keyed by field id; the script writes the first message under each field.
  • fetch only rejects on network failures. HTTP errors still resolve, with the error envelope in the body.
  • A 429 response carries Retry-After, which browser code can read because Ikiform exposes it through CORS.

With the Ikiform human check

The interstitial check page only appears for normal browser navigations. A fetch post to a form with the Ikiform check gets 403 challenge_required instead. Use challenge from the SDK through your bundler, or let the form post without JavaScript.