How to capture response of form.submit with JavaScript?

Sometimes, we want to capture response of form.submit with JavaScript.

In this article, we’ll look at how to capture response of form.submit with JavaScript.

How to capture response of form.submit with JavaScript?

To capture response of form.submit with JavaScript, we can listen for the form’s submit event.

For instance, we write

<form id="myFormId" action="/api/process/form" method="post">
  ...
  <button type="submit">Submit</button>
</form>

to add a form with some fields.

Then we write

document.forms["myFormId"].addEventListener("submit", async (event) => {
  event.preventDefault();
  const resp = await fetch(event.target.action, {
    method: "POST",
    body: new URLSearchParams(new FormData(event.target)),
  });
  const body = await resp.json();
  console.log(body);
});

to get the form with ID myFormId with

document.forms["myFormId"]

And we call addEventListener on it with 'submit' and the form submit event callback to submit the form when the submit button is clicked.

In the event handler callback, we call fetch with the event.target.action, which is the value of the form’s action attribute, and an object that has the request method and body.

We get the form data from the form with

new FormData(event.target)

And convert it to a query string with URLSearchParams.

Finally we get the response from resp.json.

Conclusion

To capture response of form.submit with JavaScript, we can listen for the form’s submit event.