Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my FormData object always empty?

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.

like image 718
N.Bar Avatar asked Aug 01 '18 15:08

N.Bar


People also ask

Why form data is empty?

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.

How get all values from FormData?

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.

Can I append object in FormData?

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.

How do I append a file to FormData?

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.


1 Answers

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:

  • As formData.entries() returns an interator object, there is no length property.
  • There is also no indexer [] defined. So you need to retrieve values using the get() method as shown by Daniel Beck in his answer.
like image 86
Krisztián Balla Avatar answered Sep 28 '22 23:09

Krisztián Balla