Submitting a form via AJAX using FormData in JavaScript

With FormData you can automatically submit all form fields to a server. Let's see how it's done.

Suppose we have the following form, in which the inputs have the name attributes:

<form action="" method="GET"> <input name="num1"> <input name="num2"> <input type="submit"> </form>

Let's submit this form via AJAX. First, we get a reference to the form into a variable:

let form = document.querySelector('form');

Now, in the request body, we specify the FormData object as data. And we will pass the reference to the form as a parameter to the object itself:

form.addEventListener('submit', function(event) { let promise = fetch('/handler/', { method: 'POST', body: new FormData(this) // we pass a reference to a form }); event.preventDefault(); });

As a result, on a server we will be able to obtain the inputs values by their names from the name attributes:

export default { '/handler/': function({post}) { console.log(post.num1); console.log(post.num2); return 'form data received'; } }

Given a form with five inputs into which numbers are entered. Submit this form to a server using the POST method. Let the server find an arithmetic mean of the entered numbers and send the result back to the browser.