How to use fetch api submit an html form

Fetch api allows asynchronous means of reading files and a more simplified way of making http requests in JavaScript.

How to submit an existing html form using fetch api;

Assuming you have html source code with a form and some input fields;

<form id="form" action="./submit" method="post"
onsubmit="handle(event)">
<input name="query">
<button>
    submit
</button>
</form>

You can pass an instance of a dom form to formData constructor as the first parameter;

const handle = function(event) {
    event.preventDefault()
    const data = new formData(event.target)

fetch('//localhost/api/post', {
    method: 'POST',
    body: data
})
}

Fetch api returns a new pending promise to process the response you will need to await asynchronous process once ready to consume parse it as follows;

.then(response => response.json())

.then(response => console.log(response))

Comments