8808 shaares
198 private links
198 private links
The tricky part is to make sure that requests made with JavaScript work the same as with HTML.
- Implement features in HTML first
- then add javascript
Conveniently, if the HTML is done properly we can derive all the information we need.
document.querySelector('form').addEventListener('submit', (event) => {
const form = event.target;
const url = new URL(form.action || window.location.href);
const formData = new FormData(form);
const searchParameters = new URLSearchParams(formData);
const options = {
method: form.method,
};
if (options.method === 'post') {
// Modify request body to include form data
options.body =
form.enctype === 'multipart/form-data' ? formData : searchParameters;
} else {
// Modify URL to include form data
url.search = searchParameters;
}
fetch(url, options);
event.preventDefault();
}
For POST requests, we’ll send the data in the request body.
- If the form explicitly sets the enctype to 'multipart/form-data', it’s safe to use FormData in the body.
- Otherwise, we can fall back to URLSearchParams.
For GET requests, we’ll send the data in the request URL with the URLSearchParams object.
For the response: the header Accept: 'application/json'
tells the server that json is awaited by the client else return HTML or a redirect :)
if we want to support HTML forms, we are though limited to GET and POST. But there is a nice workaround too:
- The GET and POST routes don’t change.
- The PATCH and DELETE routes become POST.
- We append the “methods”
/update
and/delete
to their respective routes.
Also: to include extra data in your request, you can use and input with the name, value, and the type of “hidden”.
It is also important that not all progressive enhancement is a zero sum game.