JavaScript and AJAX
Submit forms to FormDB with fetch, FormData or JSON, handle success and error responses, and use the React and Vue examples provided.
This page shows how to submit a form with JavaScript, so the visitor stays on your page and you control the success and error messages. It includes plain JavaScript, React and Vue examples, and explains how cross-site requests are handled.
Submitting in the background like this is often called AJAX. In modern browsers you do it with the built-in fetch function.
The one header to remember
Send the header Accept: application/json with every JavaScript submission. It tells FormDB to reply with JSON instead of a web page.
Without it, FormDB treats the request like a normal browser form post. If your form has a redirect URL, FormDB answers with a redirect, and fetch will try to follow it to another site and fail.
Send an existing form with FormData
FormData collects every named field in a form, including files. This is the approach that works for all forms.
<form id="contact-form">
<label for="email">Email</label>
<input type="email" id="email" name="email" required />
<label for="message">Message</label>
<textarea id="message" name="message" required></textarea>
<input type="text" name="_gotcha" tabindex="-1" autocomplete="off" style="display:none" />
<button type="submit">Send</button>
<p id="form-status" role="status"></p>
</form>
<script>
const form = document.getElementById("contact-form");
const status = document.getElementById("form-status");
form.addEventListener("submit", async (event) => {
event.preventDefault();
status.textContent = "Sending...";
try {
const response = await fetch("https://api.formdb.io/f/your-form-id", {
method: "POST",
headers: { Accept: "application/json" },
body: new FormData(form),
});
const body = await response.json();
if (body.ok) {
form.reset();
status.textContent = "Thanks! We received your message.";
} else {
status.textContent = body.error.message;
}
} catch (err) {
status.textContent = "Network error. Please try again.";
}
});
</script>Do not set a Content-Type header yourself when the body is FormData. The browser sets the right one, including a boundary value that FormDB needs to read the fields and files.
Send JSON
If you already have the values in JavaScript, you can send a JSON object. JSON cannot carry files.
const response = await fetch("https://api.formdb.io/f/your-form-id", {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
email: "jane@example.com",
message: "Hello from fetch",
}),
});
const body = await response.json();The body must be a JSON object. Nested objects and arrays inside it are stored as they are. If you send invalid JSON, or an array or plain value at the top level, FormDB treats the submission as empty.
Success and error responses
A successful submission returns status 201:
{ "ok": true, "id": "V1StGXR8_Z5jdHi6B-myT" }id is the submission's ID. It is null when the honeypot field was filled in, because nothing was stored.
A rejected submission returns an error status and this shape:
{
"ok": false,
"error": {
"code": "validation_failed",
"message": "Email must be a valid email address. (+1 more)",
"fields": {
"email": { "message": "Email must be a valid email address.", "rule": "type" },
"message": { "message": "Message is required.", "rule": "required" }
}
}
}error.codeis a stable identifier you can test in code.error.messageis a sentence you can show to the visitor.error.fieldsis only present forvalidation_failed. It is keyed by field name, with one message per field.
Note: The error text is atbody.error.message, notbody.message. If you copy a React, Vue or jQuery snippet from the dashboard, check that it readsbody.error.message, otherwise it will always show its fallback text.
To show errors next to each field:
if (!body.ok && body.error.fields) {
for (const [name, detail] of Object.entries(body.error.fields)) {
const target = document.querySelector(`[data-error-for="${name}"]`);
if (target) target.textContent = detail.message;
}
}The full list of error codes is in the Endpoint reference.
React example
import { useState } from "react";
const ENDPOINT = "https://api.formdb.io/f/your-form-id";
export function ContactForm() {
const [state, setState] = useState("idle");
const [error, setError] = useState("");
async function handleSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
setState("sending");
setError("");
try {
const response = await fetch(ENDPOINT, {
method: "POST",
headers: { Accept: "application/json" },
body: new FormData(form),
});
const body = await response.json();
if (body.ok) {
form.reset();
setState("sent");
} else {
setError(body.error.message);
setState("error");
}
} catch (err) {
setError("Network error. Please try again.");
setState("error");
}
}
if (state === "sent") {
return <p>Thanks! We received your message.</p>;
}
return (
<form onSubmit={handleSubmit}>
<label htmlFor="email">Email</label>
<input type="email" id="email" name="email" required />
<label htmlFor="message">Message</label>
<textarea id="message" name="message" required />
<input type="text" name="_gotcha" tabIndex={-1} autoComplete="off" style={{ display: "none" }} />
{state === "error" && <p role="alert">{error}</p>}
<button type="submit" disabled={state === "sending"}>
{state === "sending" ? "Sending..." : "Send"}
</button>
</form>
);
}Vue example
<script setup>
import { ref } from "vue";
const ENDPOINT = "https://api.formdb.io/f/your-form-id";
const state = ref("idle");
const error = ref("");
async function handleSubmit(event) {
const form = event.target;
state.value = "sending";
error.value = "";
try {
const response = await fetch(ENDPOINT, {
method: "POST",
headers: { Accept: "application/json" },
body: new FormData(form),
});
const body = await response.json();
if (body.ok) {
form.reset();
state.value = "sent";
} else {
error.value = body.error.message;
state.value = "error";
}
} catch (err) {
error.value = "Network error. Please try again.";
state.value = "error";
}
}
</script>
<template>
<p v-if="state === 'sent'">Thanks! We received your message.</p>
<form v-else @submit.prevent="handleSubmit">
<label for="email">Email</label>
<input type="email" id="email" name="email" required />
<label for="message">Message</label>
<textarea id="message" name="message" required></textarea>
<input type="text" name="_gotcha" tabindex="-1" autocomplete="off" style="display:none" />
<p v-if="state === 'error'" role="alert">{{ error }}</p>
<button type="submit" :disabled="state === 'sending'">Send</button>
</form>
</template>CORS behaviour
CORS (cross-origin resource sharing) is the browser rule that decides whether a page on one site may call an address on another. FormDB allows cross-origin submissions from any website, so fetch works from your own domain without extra setup.
- Allowed methods are
POSTandOPTIONS. - The only request headers you may send are
Content-TypeandAccept. If you add custom headers, the browser blocks the request. - Cookies are not used. You do not need
credentials: "include". - Error responses carry the same CORS headers, so your code can always read
body.error.
If you restrict a form to certain websites with allowed domains, requests from other sites receive 403 origin_not_allowed. See Blocking and allowed domains.
Captcha with JavaScript
If the form uses a captcha, the token must be part of the submission. With a visible widget placed inside the form, new FormData(form) picks the token up automatically. See Captcha.
Next steps
- Endpoint reference: every status code and limit.
- Validation rules: make FormDB check fields for you.
- File uploads: send files with FormData.
Ready to try it? Create a free account and send your first submission.