I’m having trouble posting a form using fetch.
Here’s my code, when I get to my PHP code I can’t find any of the posted form values
Here’s my JS code.
I don’t get any JS errors and it returns static information from my destination. I just can’t return or error log any posted data.
“`
const registerForm = document.getElementById(“registerForm”);
registerForm.addEventListener(“submit”, handleFormSubmit);
async function handleFormSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const url = “functions/validateUser.php”;
try {
const formData = new FormData(form);
console.log(formData);
const data = await postFormDataAsJson({ url, formData });
console.log(data);
} catch (error) {
console.error(error);
}
}
async function postFormDataAsJson({ url, formData }) {
const plainFormData = Object.fromEntries(formData.entries());
const formDataJsonString = JSON.stringify(plainFormData);
const fetchOptions = {
method: “POST”,
headers: {
“Content-Type”: “application/json”,
Accept: “application/json”,
},
body: formDataJsonString,
};
const response = await fetch(url, fetchOptions);
if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
return response.json();
}