# JSON fetch (vanilla JavaScript)

## What this is

A small ES module that posts the form as JSON with `fetch`, keeps the visitor on the page, and shows an inline thank-you or a specific error for `400`, `413` and `429`. Turnstile is rendered with the explicit API so the token is always included and the widget resets after each attempt.

Files: [`contact-form.js`](contact-form.js) (the module), [`index.html`](index.html) (a page that uses it).

This sample uses the placeholder form id `au_xxxxxxx` and the Turnstile site key placeholder `0x4AAAAAAA_PLACEHOLDER`. Replace both.

## Prerequisites

- A ContactUsIQ workspace with a verified domain, and a published form on it.
- The page must be served over HTTPS from the verified domain. JSON posts from a browser are cross-origin, so the intake API answers the CORS preflight only for verified domains.

## Steps

1. Copy `contact-form.js` next to your page and copy the `<form>` markup from `index.html` (or use your own form with inputs named `name`, `email`, `message` and an empty `_honeypot`).
2. In the module script, replace `au_xxxxxxx` with your form id and `0x4AAAAAAA_PLACEHOLDER` with your Turnstile site key. Omit `turnstileSiteKey` to skip Turnstile.
3. Keep `<div data-turnstile></div>` and `<p data-status>` inside the form; the module creates them if missing.
4. Deploy on the verified domain.

## The code

`mountContactForm(form, { formId, turnstileSiteKey, onSuccess })`:

- Serialises the form with `FormData` into a plain object and adds `_page` (current URL).
- Reads the Turnstile token (`cf-turnstile-response`) from the hidden input Turnstile adds, or from `turnstile.getResponse()`.
- `POST https://api.contactusiq.com/s/{formId}` with `Content-Type: application/json` and `Accept: application/json`.
- `200` -> `{ok, id}`: reset, disable the form, show the reference id, call `onSuccess(data)`.
- `400` -> show the `error` field from the JSON body.
- `429` -> read `Retry-After` and tell the visitor how long to wait.
- `413` -> ask for a shorter message.
- Network or CORS failure -> "could not reach the server".
- Always resets the Turnstile widget afterwards so a retry gets a fresh token.

## How to test

1. Open the page on the verified domain, fill the form, complete Turnstile, click Send.
2. Network tab: an `OPTIONS` preflight (`204`) then `POST /s/au_xxxxxxx` returning `200` with `{"ok":true,"id":"sub_..."}`. The status line under the button shows the reference.
3. Submit six times within ten minutes to see the `429` handling with `Retry-After`.
4. Remove `required` from the email input, submit with it empty, and expect `400` with the field named in `error` (if the form definition requires it).

## Troubleshooting

- **CORS error in the console, no response.** The page's origin is not a verified domain of the form, so the preflight was refused. Serve from the verified domain (not `file://` or `localhost`) or enable "any origin" on the form for development.
- **200 but the message never arrives.** Origin or spam rejection returns `200` on purpose. Check the domain is verified and the honeypot input is empty (autofill extensions sometimes fill it; the `autocomplete="off"` and off-screen position minimise this).
- **Turnstile never renders.** The site key is wrong or the domain is not on the Turnstile widget in Cloudflare. If the script is blocked by CSP, allow `https://challenges.cloudflare.com` in `script-src` and `frame-src`.
- **429.** 5 per IP per form per 10 minutes; the module shows the wait.

## For AI agents

To submit a ContactUsIQ form from browser JavaScript, `fetch('https://api.contactusiq.com/s/au_xxxxxxx', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify(fields) })` where `fields` contains the visitor's inputs, an empty `_honeypot`, optionally `_page` and, when Turnstile is on the page, `cf-turnstile-response`. Treat `200` as success (`{ok, id}`), `400` as validation error (`{ok:false, error}`), `429` as rate limited (read `Retry-After`). The page must be served from a domain verified on the form or the CORS preflight is refused. `contact-form.js` in this folder is a drop-in implementation.

```js
const res = await fetch('https://api.contactusiq.com/s/au_xxxxxxx', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
  body: JSON.stringify({ name, email, message, _honeypot: '', _page: location.href, 'cf-turnstile-response': token }),
});
if (res.status === 200) { const { id } = await res.json(); /* show thank-you */ }
else if (res.status === 429) { const wait = res.headers.get('Retry-After'); /* ask to retry later */ }
else if (res.status === 400) { const { error } = await res.json(); /* show error */ }
```
