You can POST HTML <form> data using the JavaScript fetch() method in the following steps:
- Select the HTML
<form>element; - Handle form submission event and prevent the default action;
- Pass the form to an new instance of
FormDataobject; - Specify
methodasPOSTandbodyas theFormDatainstance as an option tofetch(url, options)call; - Wait for the server to respond, and read the response it sends back.
Once you submit the form data, you need to have a server-side script that handles, processes and responds to the form submission request.
For example, you can implement this in the following way:
// 1: select HTML form element
const form = document.getElementById('myForm');
// 2.1: handle form submission
form.addEventListener('submit', async (event) => {
// 2.2: prevent default submission action
event.preventDefault();
try {
// 3: pass form to a new `FormData` instance
const formData = new FormData(form);
// 4: specify `method` and `body` options to the `fetch` call
const response = await fetch('your-url', {
method: 'POST',
body: formData,
});
// 5: wait for server response and read it
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
});
You can achieve the same using the Promise syntax, for example, in the following way:
// ...
fetch('your-url', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Error:', error);
});
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.