Modern Answer without XHR or jQuery
It's 2022, we don't need to use old tools like XHR or jQuery when we have the Fetch API and the FormData API!
The first thing we need to do is prevent the default form submission behavior from occurring with event.preventDefault()
:
form.addEventListener("submit", function(event){
event.preventDefault();
// ...
});
Now we need to replace the submission behavior with our own AJAX request. The Fetch API makes it pretty simple to post form data - just create a new FormData
object, populating it with the form's values, and use it as the body of a fetch request:
fetch(form.action, {
method: "post",
body: new FormData(form)
});
Note that this submits an HTTP request using the multipart/form-data
encoding type. If you need to post the data using the application/x-www-form-urlencoded
format, create a new URLSearchParams
object from the FormData
object and use that as the fetch's body.1
fetch(form.action, {
method: "post",
body: new URLSearchParams(new FormData(form))
});
Finally, if you instead want to submit the HTTP request as JSON, use the following:2
fetch(form.action, {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(Object.fromEntries(new FormData(form)))
});
Here's a full code example:
let form = document.querySelector("form");
form.addEventListener("submit", function(event){
event.preventDefault();
fetch(form.action, {
method: "post",
body: new URLSearchParams(new FormData(form)) // for application/x-www-form-urlencoded
// body: new FormData(form) // for multipart/form-data
});
});
<form method="POST">
<input name="name" placeholder="Name" />
<input name="phone" type="tel" placeholder="Phone" />
<input name="email" type="email" placeholder="Email" />
<input name="submit" type="submit" />
</form>
1 What's the difference between the two encoding types?
2 Code based on this answer to "How to convert FormData (HTML5 object) to JSON". Note that if a key is duplicated, only the last value is used.