Fraser Boag

Using FormData when posting data to the server using JavaScript Fetch

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:

    var formData = new FormData();
    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


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!