Categories
JavaScript Answers

How to capture response of form.submit with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *