I am working with express, mongoose and JavaScript to create a single page application. The code works , except I dont want to keep form info in the URL with post request. I tried redirect but it kind ended in loop - I think.
I am not using form method="post" because it will redirect the page and this is a SPA. I would like not to show this or redirect from the URL to the same page without the query info.
http://localhost:2000/?firstName=John&lastName=James&age=40
This is the form (index.html) --
<form id="formId">
<input type="text" name="firstName">
<input type="text" name="lastName">
<input type="text" name="age">
<button type="submit" onclick="processForm(event)">Save</button>
</form>
Here is the JS for the form handling :
function processForm(event){
var formData = new FormData(document.forms[0])
const queryString = Object.fromEntries(
Array.from(formData.keys()).map(key => [
key, formData.getAll(key).length > 1 ?
formData.getAll(key) : formData.get(key)]));
postData(queryString);
}
async function postData(data) {
fetch('/people', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
})
.then(response =>response.json())
.then(data => console.log('Success:', data))
.catch((error) => {
console.error('Error:', error);
});
};
Since this is an SPA application and you want to handle the form via AJAX, you should stop the default form handler for the page (which is a redirection).
You can do that using event.preventDefault()
So your code should look like this:
function processForm(event){
event.preventDefault();
...rest of the form handling logic
}
Additionally you probably want to use the form.onsubmit event rather then button.onclick event to send the data.