Fetch API JSON Request Example
This example will walk you through the necessary steps to make a form submission using the popular JSON Fetch API. Keep in mind, the Fetch API is not fully supported in Internet Explorer so you may want to consider using a library like Axios in a production environment.
Submitting an HTML Form using JavaScript and the Fetch API
In the example below, we're going to write a simple Vanilla JS function to handle the submission of an HTML form on a page. We'll attach an onSubmit handler and process the request using Fetch.
Add the HTML form to your page with a unique ID.
Add a standard HTML form to your site, and include a unique ID so the submit handler can identify the proper form.
<form id="form" method="POST"> <input type="text" name="name" placeholder="Enter name" required></input> <input type="email" name="email" placeholder="Enter email" required></input> <textarea placeholder="Enter message" name="message" required></textarea> <button type="submit">Send</button> </form>
Add a submit handler to process submit events
The script below will add a submit handler to your HTML form and then use the Fetch API to process the request. If the request is successful, a redirect URL will be returned to complete the next steps.
Next steps after a submission may include: reCAPTCHA redirect, Stripe Checkout redirect, and/or a thank-you page redirect. You'll want to isolate the URL provided and redirect the user to it.
<script> let form = document.getElementById("form"); form.addEventListener("submit", async (e) => { e.preventDefault(); const config = { method: "POST", body: new FormData(e.target), }; await fetch( "{Formeezy-Endpoint}", config ) .then(async (response) => { const { redirect } = await response.json(); window.location.href = redirect; }) .catch((error) => console.log(error)); }); </script>