I am trying to understand this example for uploading JSON data.
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_json_data
I am not sure what is meant to be in the server file ( json-session.php ) so I've left it blank. I feel there must be code missing but I cant see from the Mozilla site what is meant to be here to get this example working. I am getting an error that there's an unexpected end to the JSON.
Ps, this example is a follow on from my previous question below; though I've switched to the PHP version - I am trying to do the first part of floatinglomas answer here by posting data from the client to the server.
Using global variables properly in node.js or is there a better way of doing this?
This is my code that I'm working with
<!DOCTYPE html>
<html>
<head>
<title>Buy cool new product</title>
<link rel="stylesheet" href="style.css">
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<form id="form1">
<input onclick="clickFunction()" id="new-button" type="submit" value="click">
</form>
</body>
<script type="text/javascript">
function clickFunction() {
const data = { username: 'example' };
fetch('json-session.php', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
}
</script>
</html>