I made a form tag and script. I tried to send POST. However, The formData is empty. I do not know why.
HTML code
<form id = "form" action="sample.php" method="POST">
<input name="mytext" type="text">
<input id="submit-button" type="submit" value="submit">
</form>
JavaScript code
const form = document.getElementById("form")
const submitButton = document.getElementById("submit-button")
submitButton.onclick = () => {
event.preventDefault()
var request = document.createElement('input');
const formData = new FormData(form)
const action = form.getAttribute("action")
const options = {
method: 'POST',
body: formData,
}
fetch(action, options).then((e) => {
if (e.status === 200) {
alert("sent")
return
}
alert("fail")
})
}
PHP code
$text= $_POST['mytext'];
I put console.log(formData) in fetch(action, options).then((e) => {} .As far as I can see,formData is empty. enter image description here
I tried to use
const f1 = document.getElementById('mytext');
const fd = new FormData(f1);
instead of
const form = document.getElementById("form")
However, this error happened.
Uncaught TypeError: Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'. at submitButton.onclick (test.php:213:14)