Send & Receive JSON With Javascript Fetch

Welcome to a tutorial and examples on how to send and receive JSON data with the Javascript Fetch API. Need to send JSON encoded objects and arrays with fetch? Receive JSON data from the server? A little bit of JSON magic is required.

To send as JSON data with fetch:

  • var data = JSON.stringify({ "KEY" : "VALUE" });
  • var head = { "Content-Type" : "application/json" };
  • fetch("URL", { method: "POST", headers: head, body: data });

To receive JSON data with fetch:

  • fetch("URL")
  • .then((result) => { return result.json(); }
  • .then((data) => { console.log(data); });

That covers the basics, but read on for the detailed examples!

ⓘ 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 Fetch JSON 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.

 

 

WORKING WITH JSON WITH FETCH

All right, let us now get into the examples of getting and sending JSON data with Javascript fetch.

 

SEND JSON DATA WITH FETCH

THE JAVASCRIPT

1a-json-send.html
 <script>
function jsend () {
  // (A) DATA OBJECT
  var data = {
    name : "Jon Doe",
    email : "jon@doe.com"
  };
 
  // (B) FETCH POST JSON
  fetch("1b-dummy.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(data)
  })
 
  // (C) RETURN SERVER RESPONSE AS TEXT
  .then((result) => {
    console.log(result);
    if (result.status != 200) { throw new Error("Bad Server Response"); }
    return result.text();
  })
  .then((response) => {
    console.log(response);
  })
 
  // (D) HANDLE ERROR
  .catch((error) => { console.log(error); });
}
</script>
 
<input type="button" value="JSON Send" onclick="jsend()"/>

That’s right, this is pretty much the “expanded version” of the introduction snippet.

  1. Dummy data. Period.
  2. To send as JSON data with fetch().
    • Set the method as POST.
    • Set the JSON headers.
    • Append the JSON data in the body itself.
  3. For the uninitiated, fetch() will consider it a success as long as the server responds. Even when the server runs into errors such as 404 (not found), 403 (unauthorized), and 500 (server error). So it is better to do a manual result.status == 200 (OK) check here.
  4. Handle any errors, optional, but highly recommended.

 

 

DUMMY PHP

1b-dummy.php
<?php
$data = json_decode(file_get_contents("php://input"), true);
print_r($data);

Nothing much to see here… Just handle the JSON data in your own server-side script.

 

RECEIVE JSON DATA WITH FETCH

THE JAVASCRIPT

2a-json-recv.html
 <script>
function jget () {
  // (A) FETCH REQUEST
  fetch("2b-user.json")
 
  // (B) RETURN SERVER RESPONSE AS TEXT
  .then((result) => {
    console.log(result);
    if (result.status != 200) { throw new Error("Bad Server Response"); }
    return result.json();
  })
  .then((response) => {
    console.log(response);
  })
 
  // (C) HANDLE ERROR
  .catch((error) => { console.log(error); });
}
</script>
 
<input type="button" value="JSON Get" onclick="jget()"/>

Well, just use result.json() to automatically parse the fetched JSON data back into an array/object.

 

 

DUMMY JSON DATA

2b-user.json
{"name":"Jon Doe","email":"jon@doe.com"}

Dummy JSON data… Generate your own JSON data in your own project.

 

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 CHEATSHEET

Javascript Fetch JSON (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 *