Fraser Boag

Using FormData when posting data to the server using JavaScript Fetch

Back to all notes
Dev
17th January '20

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
    });

});

More notesAll notes

Get in touch  —  fraser.boag@gmail.com
Copyright © Fraser Boag 2013 - 2024. All rights reserved.