I'm trying to post (as in request type of POST) some JSON data to a PHP back end page using Fetch, but for some reason, the PHP page is reading the POST as empty.
Form Markup
<form action="add_to_mailchimp.php" method="POST">
<input type="text" name="email" placeholder="Enter your email" />
<button type="submit">Go</button>
</form>
Javascript:
document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector('form');
form.addEventListener('submit', (e) => {
e.preventDefault();
const payload = {
// email: document.querySelector('[name="email"]').value,
email: 'dpa@gmail.com', // hard code value just for example
};
console.log('about to submit %o', payload);
fetch('add_to_mailchimp.php', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log(response);
return response.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
});
});
PHP
<?php
print json_encode(array('postObj' => $_POST, 'reqType' => $_SERVER['REQUEST_METHOD'));
die;
?>
The following is written to the console upon submitting the form.
{postObj: [], reqType: "POST", [[Prototype]]: Object}
When I remove the javascript and allow the form to submit normally and add the following to the PHP:
print '<pre>';
print_r($_POST);
print '</pre>';
I get:
Array
(
[email] => dp@gail.com
)
Where dp@gmail.com
is whatever value is entered into the text field. I've been banging my head into the wall trying to figure this out for the past hour and am officially out of ideas. Can anyone shed some light on this for me? Thanks!