Using FormData when posting data to the server using JavaScript Fetch

Back to all posts
Snippets
17th January 2020

As someone who writes a lot of back ends in PHP and a lot of front ends in JavaScript, I often find myself needing to POST data from a form to be processed on the server.

Using JavaScript's excellent Fetch API, I've found the easiest way to do this is by encoding my fields as FormData before passing them through in the body of the Fetch request - especially when only dealing with small amount of data. On the server side, this allows me to interact with the data easily using $_POST.

For example, here's how I pass data to my newsletter sign up endpoint on this website:

newsletterForm.addEventListener('submit', (e) => {

    e.preventDefault();

    const formData = new FormData();
    formData.append('email', emailField.value);

    fetch(newsletter_endpoint, {
        method: 'post',
        body: formData
    })
    .then((response) => response.json())
    .then((data) => {
        // Confirmation
    });

});

Keep in touch

Stick your email in the box and I'll let you know about anything interesting I have to share. No spam ever, of course.