I have a JavaScript Code with a variable "dictionary" with JSON content. I need a function (saveData()
) which sends the Data to the PHP back-end to save it in the database. That's my current code:
async function saveData() {
try {
let id = getCookie('hhb-id') | 0;
const response = await fetch(`api.php?id=${id}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(dictionary)
});
if (!response.ok) {
let responseData = await response.json();
console.error('An error occurred while saving the data (Request): ', responseData);
}
else {
console.log('Data saved successfully: ', await response.json());
}
} catch (error) {
console.error('An error occurred while saving the data (Catch): ', error);
}
}
My problem is that here everyone can send data to the back-end and not only the JavaScript function. How have I to change my code to do that?
That's my PHP code (api.php):
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_GET['id']) and $_GET['id'] > 0) {
try {
$data = json_decode(file_get_contents('php://input'));
// save data to database
...
} catch (Exception $e) {
...
}
}
}