In JavaScript is pretty simple to send a form using the Fetch API.
We can create the following two utility functions.
'use strict';
// Sets the HTTP header Content-Type as application/x-www-form-urlencoded
async function postData(url = '', data = '') {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: data
});
return response.json();
}
// Serializes form fields as key=value
const serializeForm = form => {
const elements = form.querySelectorAll('input,select,textarea');
const data = [];
if(elements.length > 0) {
elements.forEach(element => {
if(element.getAttribute('type') !== 'submit') {
let part = element.getAttribute('name') + '=' + element.value;
data.push(part);
}
});
}
return data.join('&');
};
Then we can use them as follows:
const form = document.querySelector('#form');
form.addEventListener('submit', evt => {
evt.preventDefault();
const data = serializeForm(form);
postData('/submit', data).then(response => {
console.log(response);
});
}, false);