Recipe 7.3
Submitting a Form as JSON
You can transform FormData
data into a JavaScript object, and submit the form to an endpoint as JSON using the Fetch API.
Demo
Add User
Received form data:
Code
JavaScript
const form = document.querySelector('#user-form');
form.addEventListener('submit', event => {
event.preventDefault();
const data = new FormData(event.target);
const body = {};
for (const [key, value] of data.entries()) {
body[key] = value;
}
fetch('/api/form', {
method: 'POST',
body: JSON.stringify(body),
headers: {
'content-type': 'application/json'
}
})
.then(response => response.json())
.then(body => renderResults(body));
});
function renderResults(result) {
const resultContainer = document.querySelector('#result');
const list = resultContainer.querySelector('ul');
for (const [key, value] of Object.entries(result)) {
const item = document.createElement('li');
item.innerHTML = `<strong>${key}</strong>: ${value}`;
list.appendChild(item);
}
resultContainer.classList.remove('d-none');
}
HTML
<h3>Add User</h3>
<form id="user-form" class="mb-3">
<div class="mb-3">
<label class="form-label" for="username">Username</label>
<input required class="form-control" name="username" id="username" value="john.doe">
</div>
<div class="mb-3">
<label class="form-label" for="email">Email</label>
<input required class="form-control" name="email" id="email" value="jdoe@gmail.com">
</div>
<button class="btn btn-primary">Submit</button>
</form>
<div id="result" class="alert alert-primary d-none" role="alert">
<h4>Received form data:</h4>
<ul></ul>
</div>