I need to add some data to a form using FormData so that when the form is submitted this new piece of data is also posted, but I can't get it working. Note that I do not want to use ajax or fetch to send formData since I want the page to redirect user to a different page when he clicks the submit button.
const myForm = document.querySelector('form');
myForm.addEventListener('submit', (event) => {
event.preventDefault();
const formData = new FormData(myForm);
formData.append('age', '20');
event.target.submit();
});
As mentioned in comments the best way to do this was to prevent the normal event, submit your own formData object and then redirect by yourself.
var form = document.querySelector("form");
form.addEventListener('submit', e => {
e.preventDefault()
// build up formdata
const formData = new FormData(form);
formData.append("age", '20');
const request = new XMLHttpRequest();
request.open("POST", "submitform.php");
// redirect on success
request.addEventListener('load', function( event ) {
window.location.replace('/my-locaiton')
});
// Do whatever needed on error
request.addEventListener('error', function( event ) {
console.log('failed request..')
});
request.send(formData);
})
<form id="form" action="POST" target="redirect.html">
<input type="text" value="somtext">
<input type="submit">
</form>
If you still want to let the form do the job you could do something like this to prevent the event and then dispatch it again.. You would need to add hidden elements to the form in this case:
const form = document.getElementById('form')
const listener = async (e) => {
// prevent default action.
e.preventDefault()
// only run the listener only once.
form.removeListener('submit', listener)
// append actual data..
const ageInput = document.createElement('input')
ageInput.style.visibility = 'hidden'
ageInput.setAttribute('name', 'age')
ageInput.setAttribute('value', '20')
form.appendChild(ageInput)
// dispatch event again!
e.target.dispatchEvent(e)
}
form.addEventListener('submit', listener)