#fetchapi #javascript #json
September 18, 2018
by Matteo Bertozzo
Find more about
[development]
Basically, what we want to achieve is to store our client-generated JSON on the server, except we don’t have an existing API to call. And since we suppose to be on a LAMP server, no Javascript for server-side code!
The only thing to do is to create a PHP script that will be called by JavaScript taking advantage of the Fetch API.
Let’s start by creating a save.php file and writing in it what follows:
<?php
$content = trim(file_get_contents("php://input"));
//retrieve the current file path
$base_dir = dirname(__FILE__);
//open the file data.json and overwrite it with content
//if the file does not exist, create it
$file = fopen($base_dir."/data.json","w");
echo fwrite($file,$content);
fclose($file);
?>
Here we’re using php://input, that is a read-only stream that allows us to read raw data from the request body. It returns all the raw data after the HTTP-headers of the request, regardless of the content type. In our case, the content type will be application/json: this is why we’re not using, as an alternative, $_POST. This PHP superglobal, as a matter of fact, is only supposed to wrap data that is either application/x-www-form-urlencoded (such as forms) or multipart/form-data-encoded (such as file uploads).
To be sure of what’s been retrived let’s add a check:
<?php
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
$content = trim(file_get_contents("php://input"));
$base_dir = dirname(__FILE__);
$file = fopen($base_dir."/data.json","w");
echo fwrite($file,$content);
fclose($file);
}
?>
Now, the last part is to call this script from inside JavaScript:
fetch("save.php", {
method: "post",
mode: "same-origin",
credentials: "same-origin",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(the-content)
})
.then((response) => {
console.log = "Dati inviati!";
});
In this case, the-content is the variable holding the JSON we want to save.
And that’s all!