Future internet searchers:
For new browsers (as of 2018: Chrome, Firefox, Safari, Opera, Edge, and most mobile browsers, but not IE), fetch is a standard API that simplifies asynchronous network calls (for which we used to need XMLHttpRequest or jQuery's $.ajax).
Here is a traditional form:
<form id="myFormId" action="/api/process/form" method="post">
<!-- form fields here -->
<button type="submit">SubmitAction</button>
</form>
If a form like the above is handed to you (or you created it because it is semantic html), then you can wrap the fetch code in an event listener as below:
document.forms['myFormId'].addEventListener('submit', (event) => {
event.preventDefault();
// TODO do something here to show user that form is being submitted
fetch(event.target.action, {
method: 'POST',
body: new URLSearchParams(new FormData(event.target)) // event.target is the form
}).then((resp) => {
return resp.json(); // or resp.text() or whatever the server sends
}).then((body) => {
// TODO handle body
}).catch((error) => {
// TODO handle error
});
});
(Or, if like the original poster you want to call it manually without a submit event, just put the fetch code there and pass a reference to the form element instead of using event.target.)
Docs:
Fetch:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Other:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
That page in 2018 does not mention fetch (yet).
But it mentions that the target="myIFrame" trick is deprecated.
And it also has an example of form.addEventListener for the 'submit' event.