Javascript Send JSON Data To PHP (Simple Examples)

Welcome to a quick tutorial on how to send JSON data from Javascript to PHP. So you need to send some “JSON data” from Javascript to a PHP script? Long story short:

Use JSON.stringfy() in Javascript to encode an array/object into a string, then send it to PHP accordingly:

  • var form = new FormData();
  • form.append("data", JSON.stringify(["One", "Two"]));
  • fetch("SCRIPT.PHP", { method:"POST", body:form })
  • .then(res => res.text())
  • .then(txt => { DO SOMETHING });

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

 

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

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

 

EXAMPLE CODE DOWNLOAD

Source code on GitHub Gist

Just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

 

SEND JSON DATA TO PHP

All right, let us get into the examples of sending JSON data from Javascript to PHP.

 

EXAMPLE 1) SEND JSON DATA WITH POST

1-json-post.html
<!-- (A) HTML FORM -->
<form id="demoA" onsubmit="return demoA()">
  <input type="text" name="name" required value="Job Doe">
  <input type="email" name="email" required value="job@doe.com">
  <input type="submit" value="Go">
</form>
 
<!-- (B) JAVASCRIPT -->
<script>
function demoA () {
  // (B1) GET FORM DATA, CONVERT TO JSON
  var form = new FormData(document.getElementById("demoA")),
      data = JSON.stringify(Object.fromEntries(form.entries()));
  console.log(data); // this is a string!

  // (B2) DATA TO SEND TO PHP
  var send = new FormData();
  send.append("data", data);

  // (B3) SEND VIA POST
  fetch("x-dummy.php", { method:"post", body:send })
  .then(res => res.text())
  .then(txt => {
    console.log(txt); // server response
    // do your stuff after server response
  })
  .catch(err => console.error(err));

  // (B4) PREVENT FORM SUBMIT
  return false;
}
</script>

Keep calm and study slowly, there’s no need to panic.

  • (A) This is the usual HTML form, we will use function demoA() to process it on submission.
  • (B1) var form = new FormData(HTML FORM) will automatically get all form fields and values.
  • (B1) Then, we format the form data into a JSON-encoded string.
    • Object.fromEntries(form.entries()) will return the object { name : "Job Doe", email : "job@doe.com" }
    • As in the introduction, JSON.stringify() will turn the object into a JSON-encoded string.
  • (B2 & B3) Now that we have the “JSON data”, all that’s left is to send it to the PHP script.

P.S. If you do not know what fetch() is, I will leave some links below to another tutorial.

 

 

EXAMPLE 2) SEND JSON DATA WITH GET

2-json-get.html
<!-- (A) HTML FORM -->
<form id="demoB" onsubmit="return demoB()">
  <input type="text" name="name" required value="Joe Doe">
  <input type="email" name="email" required value="joe@doe.com">
  <input type="submit" value="Go">
</form>

<script>
function demoB () {
  // (B1) GET FORM DATA, CONVERT TO JSON
  var form = new FormData(document.getElementById("demoB")),
      data = JSON.stringify(Object.fromEntries(form.entries()));
  console.log(data); // this is a string!

  // (B2) DATA TO SEND TO PHP
  var send = new URLSearchParams();
  send.append("data", data);

  // (B3) SEND VIA GET
  fetch("x-dummy.php?" + send.toString())
  .then(res => res.text())
  .then(txt => {
    console.log(txt); // server response
    // do your stuff after server response
  })
  .catch(err => console.error(err));

  // (B4) PREVENT FORM SUBMIT
  return false;
}
</script>

Look no further. This is the same example as above, except that we are sending via GET instead of POST. A couple of small differences here:

  • (B2) Instead of new FormData(), we use new URLSearchParams() instead.
  • (B3) For GET, we append the data to the end of the URL. That is, "x-dummy.php?" + send.toString().

 

 

EXAMPLE 3) SEND JSON DATA WITHOUT HTML FORM

3-json-no-form.html
<!-- (A) TEST BUTTON -->
<input type="button" value="Go" onclick="demoC()">
 
<!-- (B) JAVASCRIPT -->
<script>
function demoC () {
  // (B1) JSON ENCODE DATA TO SEND
  var data = JSON.stringify({
    name : "Joy Doe",
    email : "joy@doe.com"
  });
 
  // (B2) FORM DATA
  var send = new FormData();
  send.append("data", data);
 
  // (B3) SEND DATA TO PHP VIA POST
  fetch("x-dummy.php", { method:"post", body:send })
  .then(res => res.text())
  .then(txt => {
    console.log(txt); // server response
    // do your stuff after server response
  })
  .catch(err => console.error(err));
}
</script>

That’s right, we don’t even need an HTML form in modern Javascript to send data to the server. Take note of how we can append more data to FormData and URLSearchParams.

 

 

EXTRAS

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

 

EXTRA) HOW ABOUT PHP?

x-dummy.php
<?php
// (A) ECHO POST & GET DATA
print_r($_POST);
print_r($_GET);
 
// (B) JSON DECODE TO GET ARRAY
// $data = json_decode($_POST["data"], true);
// $data = json_decode($_GET["data"], true);
// print_r($data);

Once again, $_POST["data"] $_GET["data"] is just a JSON-encoded string. We can do a json_decode() in PHP to get the object/array.

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you to better understand JSON, and if you have anything to share 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 *