formEle
to the back-end using an Ajax request:const submit = function (formEle) {return new Promise(function (resolve, reject) {// Serialize form data// See https://htmldom.dev/serialize-form-data-into-a-query-stringconst params = serialize(formEle);// Create new Ajax requestconst req = new XMLHttpRequest();req.open('POST', formEle.action, true);req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');// Handle the eventsreq.onload = function () {if (req.status >= 200 && req.status < 400) {resolve(req.responseText);}};req.onerror = function () {reject();};// Send itreq.send(params);});};
serialize
function serializes all the form data into a query string. You can see how it's implemented in this post.const formEle = document.getElementById(...);submit(formEle).then(function(response) {// `response` is what we got from the back-end// We can parse it if the server returns a JSONconst data = JSON.parse(response);...});