I'm trying to add some data to formData like this:
params = {'code': 'h1'}
const formData: FormData = new FormData();
formData.append('parameters', JSON.stringify(params));
When I try to get the data from the formData like this: formData['parameters']
it returns undefined
and formData.entries.length
is 0
.
I looked at some sites and saw that this is the way to do that.
What am I doing wrong?
Thanks.
When you initialize FormData() from a form element, it'll only map input fields that have a name attribute. Only these mapped input fields are included in the form data that is sent in requests. Hence, when none of the input fields are mapped, the form data will be empty.
getAll() The getAll() method of the FormData interface returns all the values associated with a given key from within a FormData object. Note: This method is available in Web Workers.
The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
We use the append method of FormData to append the file, passed as a parameter to the uploadFile() method, to the file key. This will create a key-value pair with file as a key and the content of the passed file as a value.
Your FormData
object is actually not empty. The way you are trying to access the data after appending it, is wrong.
For me the following works:
const params = {'code': 'h1'}
const formData = new FormData();
formData.append('parameters', JSON.stringify(params));
for (const entry of formData.entries())
{
document.write(entry);
}
Side notes:
formData.entries()
returns an interator object, there is no length
property.[]
defined. So you need to retrieve values using the get() method as shown by Daniel Beck in his answer.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With