My goal is to get the value of a selector on 1 page. I want to
have a user select a year and update the page when selected a year.
Without the $_GET function.
I will demonstrate it with steps, to understand it a bit more.
- Step 1: This is the select element that the user is going to press on a year The selector
- Step 2: There should be an
echowhat the user has selected. For example; I choose 2019 > there should be aechosomewhere which prints2019.
This is getData.php
<?php
echo file_get_contents('php://input');
echo json_decode($_POST["year"]);
echo $_POST["year"];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/chartSelector.js" defer></script>
</head>
<body>
<div>
<select name="jaarKiezer" id="jaarKiezer" onchange="changeData()">
<option selected disabled>Choose a year</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
</select>
</div>
</body>
</html>
This is chartSelector.js
console.log("connected with js");
function changeData() {
let yearJS = document.getElementById("jaarKiezer").value;
console.log("changed to " + yearJS);
getData(yearJS);
}
function getData(yearJS) {
let formData = new FormData();
formData.append("year", yearJS);
fetch("../getData.php", {
"body": formData,
"method": "POST"
}).catch(error => console.error(error));
}
In the
network tab on preview you see its working. The problem comes when I want to post the form data into php, on the 'live' page
nothing happens. Only 2 errors from getData.php: Undefined array key "year".
Some images to understand it a bit more:
- The network tab itself: Network tab
- The payload: Payload
- The preview: Preview
I've tried:
- AJAX
- Using the
JSON.stringify(formData)function. - Using Headers (Like:
header(Content-Type: application/json)).
Note: I'm using php server from the vscode extensions