I am fighting with getting my data from an html form into mySQL for 2 days, now...
While I solved maaany issues I am stuck with a (imho) empty FormData object. I have a form
<form id="pricing">
...
<input id="fromDate" name="fromDate" value=""/>
...
<input type="submit" value="Go!"/>
</form>
The data shall be transmitted without redirecting to a new page, so I chose XMLHttpRequest, supporting also outdated browsers. The code is more or less copy paste from a tutorial.
const form = document.querySelector('#pricing');
// listen for submit even
form.addEventListener('submit', (event) => {
// disable default action
event.preventDefault();
// configure a request
const xhr = new XMLHttpRequest();
xhr.open('POST', 'forms/pricing.php');
// prepare form data
let data = new FormData(form);
// set headers
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
// send request
xhr.send(data);
console.log(data);
// listen for `load` event
xhr.onload = () => {
console.log(xhr.responseText);
}
});
The landing page forms/pricing.php is reached, it successfully stores some fixed values (entered for debugging) into the database upon clicking "go". However, the $_POST var seems to be empty, my data object being stored via PDO
'fromDate' => isset($_POST["fromDate"]) ? $_POST["fromDate"] : '1',
stores '1' and not the $_POST["fromDate"]. And also in the console output of console.log(data); (where data is the FormData for POST, as seen in the 2nd snippet) I cannot find any of my data.
What am I doing wrong?