-2

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)

shinzo_abe
  • 23
  • 3
  • 1
    Can you update your code such that it better resembles a [mre]? It's not clear where in the DOM you've got your script running, which is imperative to understanding whether your first two `getElementById()` calls will actually return anything. How do you *know* definitively that "*The formData is empty*"? What did you expect to happen, and what *actually* happened? Please review [ask] – esqew Sep 29 '22 at 21:46
  • How do you know definitively that "The formData is empty"? I checked $_POST['mytext']; it was blank. – shinzo_abe Sep 29 '22 at 22:06
  • 1
    You should call `event.preventDefault()` in the click handler. Otherwise the form will be submitted normally and the page will reload. – Barmar Sep 29 '22 at 22:42
  • 1
    If you view the body data in the Network tab of Developer Tools, do you see the data being sent? – Barmar Sep 29 '22 at 22:43
  • I have checked formData by console.log. I can't seem to find anydata. I think JavaScript did not get form content. – shinzo_abe Sep 29 '22 at 23:02
  • Where can I see the formdata? in PHP or HTML I can see payload tab However ,In the post by JavaScript Payload tab does not exist. – shinzo_abe Sep 30 '22 at 20:52
  • Updated question is now a duplicate of https://stackoverflow.com/questions/57285984/failed-to-construct-formdata – esqew Oct 01 '22 at 00:10

1 Answers1

0

You forgot to add event.preventDefault() to your function, if you don't the form will cause the page to reload and no data would be sent.