JavaScript FormData

Summary: in this tutorial, you’ll learn about the JavaScript FormData API and how to post the FormData using fetch API.

Introduction to the JavaScript FormData API

Suppose you have a subscription form with two fields: name and email.

<form id="subscription">
    <h1>Subscribe</h1>
    <div id="message"></div>
    <div class="field">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" placeholder="Enter your fullname" required />
        <small></small>
    </div>
    <div class="field">
        <label for="email">Email:</label>
        <input type="text" id="email" name="email" placeholder="Enter your email address" required />
        <small></small>
    </div>
    <div class="field">
        <button type="submit" class="full" id="submit">Subscribe</button>
    </div>
</form>Code language: HTML, XML (xml)

When you click the submit button, the web browser submits the values of the name and email fields in the form to the server.

Similarly, the FormData interface allows you to construct a set of key/value pairs representing form fields and their values in JavaScript.

Once having a FormData object, you can post it to the server using the Fetch API. If you want to submit the form as if it were like the GET request, you can pass the FormData object to the URLSearchParams constructor.

Create a FormData object

The following creates a new FormData object from an HTML form element:

const formData = new FormData(form);Code language: JavaScript (javascript)

The following script shows the values of a FormData object:

const btn = document.querySelector('#submit');
const form = document.querySelector('#subscription');


btn.addEventListener('click', (e) => {
    // prevent the form from submitting
    e.preventDefault();

    // show the form values
    const formData = new FormData(form);
    const values = [...formData.entries()];
    console.log(values);
});Code language: JavaScript (javascript)

How it works.

  • First, select the submit button using the querySelector() method of the document object.
  • Next, add an event handler to handle the click event of the submit button.
  • Then, call the preventDefault() method of the event object to avoid form submission.
  • After that, create a new FormData object from the form element.
  • Finally, call the entries() method of the FormData object. Since the entries() method returns an iterator, you must use the spread operator (...).

FormData methods

The FormData object has the following methods:

append()

The append() method has two forms:

FormData.append(name, value)
FormData.append(name, value, file)Code language: JavaScript (javascript)

The append() method appends a new value onto an existing key inside a FormData object or adds the key if it does not exist.

delete()

FormData.delete(name);Code language: JavaScript (javascript)

The delete() method deletes a key/value pair by the name of the key from the FormData object.

entries()

FormData.entries()Code language: JavaScript (javascript)

The entries() method returns an iterator of all key/value pairs in the FormData object.

get()

FormData.get(name)Code language: JavaScript (javascript)

The get() method returns the first value by a key name.

getAll()

FormData.getAll(name)Code language: JavaScript (javascript)

The getAll() method returns an array of all the values by a key name.

has()

FormData.has(name);Code language: JavaScript (javascript)

The has() method returns true if the FormData object contains a key name.

keys()

FormData.keys()Code language: JavaScript (javascript)

The keys() method returns an iterator of all the keys.

set()

The set() method has two forms:

FormData.set(name, value);
FormData.set(name, value, filename);Code language: JavaScript (javascript)

The set() method sets a new value for an existing key name or adds the key/value if it does not already exist.

values()

FormData.values()Code language: JavaScript (javascript)

The values() method returns an iterator of all the values in the FormData object.

Submit the FormData using fetch API

We’ll build a simple subscription form that uses the FetchAPI to post a FormData object to the server.

The following illustrates how to submit FormData using the fetch API:

const btn = document.querySelector('#submit');
const form = document.querySelector('#subscription');
const messageEl = document.querySelector('#message');

btn.addEventListener('click', (e) => {
    e.preventDefault();
    subscribe();
});

const subscribe = async () => {
    try {
        let response = await fetch('subscribe.php', {
        method: 'POST',
        body: new FormData(form),
        });
        const result = await response.json();

        showMessage(result.message, response.status == 200 ? 'success' : 'error');
    } catch (error) {
        showMessage(error.message, 'error');
    }
};

const showMessage = (message, type = 'success') => {
    messageEl.innerHTML = `
        <div class="alert alert-${type}">
        ${message}
        </div>
    `;
};Code language: JavaScript (javascript)

In this example, we define a function named subscribe() and call it in the submit button’s click event listener. The subscribe() function is an async function because it uses the await keyword.

Inside the subscribe() function:

First, post the form data to the subscribe.php script using the fetch() method:

let response = await fetch('subscribe.php', {
    method: 'POST',
    body: new FormData(form),
});Code language: JavaScript (javascript)

Second, get the JSON response by calling the json() method of the response object:

const result = await response.json();Code language: JavaScript (javascript)

Third, show a success message if the HTTP status code is 200. Otherwise, display an error message. The message property of the result stores the success or error message.

showMessage(result.message, response.status == 200 ? 'success' : 'error');Code language: JavaScript (javascript)

Finally, define the showMessage() function that displays a success or error message:

const showMessage = (message, type = 'success') => {
    messageEl.innerHTML = `
        <div class="alert alert-${type}">
        ${message}
        </div>
    `;
};Code language: JavaScript (javascript)

Put it all together.

index.html

<!DOCTYPE html>
<html lang="en">

    <head>
        <title>JavaScript Form Demo</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="stylesheet" href="css/style.css" />
    </head>

    <body>
        <div class="container">
            <form id="subscription">
                <h1>Subscribe</h1>
                <div id="message"></div>
                <div class="field">
                    <label for="name">Name:</label>
                    <input type="text" id="name" name="name" placeholder="Enter your fullname" required />
                    <small></small>
                </div>
                <div class="field">
                    <label for="email">Email:</label>
                    <input type="text" id="email" name="email" placeholder="Enter your email address" required />
                    <small></small>
                </div>
                <div class="field">
                    <button type="submit" class="full" id="submit">Subscribe</button>
                </div>
            </form>
        </div>
        <script src="js/app.js"></script>
    </body>

</html>Code language: HTML, XML (xml)

app.js

const btn = document.querySelector('#submit');
const form = document.querySelector('#subscription');
const messageEl = document.querySelector('#message');

btn.addEventListener('click', (e) => {
    e.preventDefault();
    subscribe();
});

const subscribe = async () => {
    try {
        let response = await fetch('subscribe.php', {
            method: 'POST',
            body: new FormData(form),
        });
        const result = await response.json();

        showMessage(result.message, response.status == 200 ? 'success' : 'error');

    } catch (error) {
        showMessage(error.message, 'error');
    }
};

const showMessage = (message, type = 'success') => {
    messageEl.innerHTML = `
        <div class="alert alert-${type}">
        ${message}
        </div>
    `;
};Code language: JavaScript (javascript)

Summary

  • Use the JavaScript FormData API to capture the HTML form values.
  • Use the Fetch API to submit the FormData to the server.
Was this tutorial helpful ?