Post Form Data With Javascript Fetch (Simple Example)

Welcome to a quick tutorial and example on how to post form data using Javascript Fetch. So you have just started with the Javascript Fetch API, and wondering how to send data with it?

To post form data using Javascript Fetch, simply set the send method to “post”, and set the form data in the body.

  • var data = new FormData();
  • data.append("KEY", "VALUE");
  • fetch("URL", { method: "POST", body: data });

That covers the quick basics, but read on for the detailed example!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Post Form Data Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

POST FORM DATA WITH FETCH

All right, let us now get into the example of posting form data with Javascript Fetch.

 

HTML FORM

1-post-data.html
<form onsubmit="return sendData()">
  <input type="text" id="name" value="Jon Doe" required/>
  <input type="email" id="email" value="jon@doe.com" required/>
  <input type="submit" value="Go!"/>
</form>

For this simple example, we have a dummy HTML form with only 2 fields – Name and email.

 

JAVASCRIPT FETCH 

1-post-data.html
function sendData () {
  // (A) GET FORM DATA
  var data = new FormData();
  data.append("name", document.getElementById("name").value);
  data.append("email", document.getElementById("email").value);
 
  // (B) INIT FETCH POST
  fetch("2-dummy.php", {
    method: "POST",
    body: data
  })
 
  // (C) RETURN SERVER RESPONSE AS TEXT
  .then((result) => {
    if (result.status != 200) { throw new Error("Bad Server Response"); }
    return result.text();
  })
 
  // (D) SERVER RESPONSE
  .then((response) => {
    console.log(response);
  })
 
  // (E) HANDLE ERRORS - OPTIONAL
  .catch((error) => { console.log(error); });
 
  // (F) PREVENT FORM SUBMIT
  return false;
}

This is pretty much the “full version” of the introduction snippet, should be pretty self-explanatory:

  1. Create a FormData() object, collect all the data that needs to be sent to the server.
  2. As in the introduction, set fetch to method: "POST" and append the data body: data.
  3. Take note of if (result.status != 200) { THROW ERROR } here. For you guys who are new, fetch will consider it a “success” as long as the server responds – Even when the server responds with errors like 4o4 (not found), 403 (unauthorized), and 500 (internal server error). So, it is safer to do a manual 200 (OK) check here.
  4. The server response in a string. Use this to show a success/failure message to the user.
  5. Handle any errors. Optional, but highly recommended.

 

 

SERVER-SIDE

2-dummy.php
<?php
print_r($_POST);

Lastly, do processing on the server-side as required – This dummy PHP script simply echos whatever is being posted over.

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

LINKS & REFERENCES

 

 

INFOGRAPHIC CHEAT SHEET

Post Form Data With Javascript Fetch (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *