Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

FormData and Fetch – Javascript example

Let's take a look at how we can build a form that is submitted via the browser fetch function and packages the data using the FormData API.

While both the fetch() and the FormData API are fairly straightforward wiring them together requires a few extra steps.

By the end of this example, we will build the below form that will make a POST request to the jsonplaceholder.typicode.com endpoint and displays the results.
form preview used in the FormData and Fetch example

Building the HTML form

The HTML form is pretty straightforward. A couple of labels and input fields:

<form 
    action="https://jsonplaceholder.typicode.com/comments" 
    id="comments-form">
    <label for="user">🧑‍ Name: </label>
    <input type="text" name="name" value="John Doe"><br/>
    <label for="password">📩 Email:</label>
    <input type="text" name="email" value="john_doe@gmail.com"><br/>
    <label for="comment">💬 Comment:</label>
    <input type="text" name="comment" value="Some comment here"><br/>
  <input type="submit" value="Add comment">
</form>

Please note that the form fields must have a name attribute to be added to the FormData object. If they don't have the name they’re skipped. The id property doesn’t count.

Given that we don't want to have the default behavior for the summit event of the form we will intercept and cancel it:

const handleFormSubmit = async (e) =>  {
    e.preventDefault()
    // 1. wrap the form in a FormData object
    // 2. send the object via the fetch function
}

const fComments = document.querySelector("#comments-form")
fComments.addEventListener("submit", handleFormSubmit)

Serializing the fields of the form with the FormData API

The next step will be to wrap all of the fields of the form in a FormData object. We can easily do that with Object.fromEntries(), and after that serialize the data:

const formDataToJson = (form) => {
  const formData = new FormData(form)
  const serializedData = Object.fromEntries(formData.entries())
    return JSON.stringify(serializedData)
}

const handleFormSubmit = async (e) =>  {
    e.preventDefault()

    // 1. wrap the form in a FormData object
    const form = e.currentTarget
    const data = formDataToJson(e.currentTarget)

    // 2. send the object via the fetch function
}

Keep in mind that if you are appening arrays in formdata you will need to write your own custom serializing function.

Sending the FormFata with the fetch() function

The final step will be to send the wrapped data with the fetch() function.

For this we will make a dedicated function that will make the request:

const makeRequest = async (url, data) => {
    const options = {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
            Accept: "application/json",
        },
        body: data,
    }
    const response = await fetch(url, options)
    if (!response.ok) {
        const errorMessage = await response.text()
        throw new Error(errorMessage)
    }
    return response.json();
}

Given that we may get some errors it may be a good idea to wrap it all in a try-cath block:

const handleFormSubmit = async (e) =>  {
    e.preventDefault()

    const form = e.currentTarget
    try {
        const data = formDataToJson(e.currentTarget)
        const res = await makeRequest(form.action, data)
        console.log(res)
    } catch (er) {
        console.error(er)
    }
}

As a side note, we have used the fetch API also in the NextJs 13 GET example.

You can check out here the full codepen example.

When the user will press the submit button she/he will get a console message, confirming the POST action, similar to the one below:

{
    name: 'John Doe', 
    email: 'john_doe@gmail.com', 
    comment: 'Some comment here', 
    id: 501
}
Home Screencasts Best of Newsletter Search X