Fraser Boag

Using FormData when posting data to the server using JavaScript Fetch

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',function(e){
    e.preventDefault();
    var formData = new FormData();
    formData.append('email',emailField.value);
    fetch(newsletter_endpoint, {
        method: 'post',
        body: formData
    })
    .then((response) => response.json())
    .then((data) => {
        // Confirmation
    });
});

What do you think?

I genuinely love to talk web. If you have any civil thoughts, corrections or comments on this note, feel free to tweet or DM @fraserboag or, if you prefer, email fraser.boag@gmail.com.

Tweet

Let me send you emails

From time to time I post things which people seem to find fairly interesting, stick your email address in the box below and you'll hear about it!