Network Data and API Responses
Fetch POST Form
Form Fields Become a Saved Record
A browser module turns form controls into URL-encoded request data, sends a POST request, and renders the server confirmation.
Program
The source collects the current form values before it changes the UI. The rendered output shows the sending state first, then the saved state after the API response is parsed.
fetch_post_form.js
const form = document.querySelector('#signup-form');
const status = document.querySelector('#signup-status');
const confirmation = document.querySelector('#confirmation-code');
const fields = new URLSearchParams(new FormData(form));
form.dataset.state = 'sending';
status.textContent = 'Sending signup';
const response = await fetch('/api/signups', {
method: 'POST',
body: fields
});
const result = await response.json();
form.dataset.state = 'saved';
status.textContent = `Saved ${result.topic} for ${result.email}`;
confirmation.textContent = result.id;
FormData
`FormData` reads named controls from a form, so the request starts from what the user can already see on the page.
URLSearchParams
Wrapping form data in `URLSearchParams` produces a stable URL-encoded body for a simple POST request.
POST request
The `method: 'POST'` option tells `fetch()` to send data to the server instead of only reading a resource.
confirmation UI
The response becomes useful when code writes the server confirmation back into visible page state.