I am trying to use FormData to send user-entered data in a POST request with the fetch API. The problem is that when I create a new FormData object with the form that I've created, it keeps creating an empty object - no entries/keys/values. I'm not sure why since getting the form element returns the form correctly, it is when I call new FormData(form) that I get an empty form object. From the MDN documentation, it seems that the form should be fine to set up in separate divs which my form does. Does the form data that I'm providing need to be referenced by anything other than the input ids? Can anyone suggest how I can properly create the FormData object?
Thanks!
/*
* Add event listener on form submission
*/
document.addEventListener('DOMContentLoaded', () => {
let form = document.getElementById('calc_form');
form.addEventListener('submit', callServer);
});
/*
* Handler for form submission. Prevents the default action and calls longop() 2 times
*/
function callServer(event) {
event.preventDefault();
var form = event.currentTarget;
console.log(form); //prints the html element of calc_form, the form with the event listener
var formData = new FormData(form);
console.log(formData); //prints empty FormData object
var url = form.action;
console.log('Sending calculation request to server');
getData(url, formData)
.then(data => addData(data))
.catch(error => console.error(error));
}
HTML for form
<form id="calc_form" method="POST" action="/calculate">
<div>
<label for="first">First Value</label>
<input type="number" id="first" name="first">
<br>
<label for="second">Second Value</label>
<input type="number" id = "second" name="second">
</div>
<div>
<input type="radio" id="add" name="operator" value="add">
<label for="add">Add</label>
<input type="radio" id="subtract" name="operator" value="subtract">
<label for="subtract">Subtract</label>
<input type="radio" id="multiply" name="operator" value="multiply">
<label for="multiply">Multiply</label>
<input type="radio" id="divide" name="operator" value="divide">
<label for="divide">Divide</label>
</div>
<div>
<button type="submit">Submit</button>
</div>
<div>
<p id="results"></p>
</div>
</form>