Formdata Created from an Existing Form Seems Empty When I Log It

FormData created from an existing form seems empty when I log it

Update: the XHR spec now includes several more functions to inspect FormData objects.

FireFox has supported the newer functions since v39.0, Chrome is slated to get support in v50. Not sure about other browsers.

var form = document.querySelector('form');
var formData = new FormData(form);

for (var [key, value] of formData.entries()) {
console.log(key, value);
}

//or

console.log(...formData)

Why is FormData empty?

Their is way to access FormData

var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456);

console.log(formData.get("username"));
console.log(formData.get("accountnum"));

How to inspect FormData?

Updated Method:

As of March 2016, recent versions of Chrome and Firefox now support using FormData.entries() to inspect FormData. Source.

// Create a test FormData object
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

// Display the key/value pairs
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}

Thanks to Ghost Echo and rloth for pointing this out!

Old Answer:

After looking at these Mozilla articles, it looks like there is no way to get data out of a FormData object. You can only use them for building FormData to send via an AJAX request.

I also just found this question that states the same thing: FormData.append("key", "value") is not working.

One way around this would be to build up a regular dictionary and then convert it to FormData:

var myFormData = {
key1: 300,
key2: 'hello world'
};

var fd = new FormData();
for (var key in myFormData) {
console.log(key, myFormData[key]);
fd.append(key, myFormData[key]);
}

If you want to debug a plain FormData object, you could also send it in order to examine it in the network request console:

var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(fd);

Submitting form via Ajax - FormData always empty

The data in a FormData object is not revealed by inspecting it with console.log(). It is there, you just can't see it.

If you examine the Net tab of your developer tools, you can see the form content is being uploaded.

Screenshot

Jquery ajax FormData is always empty

         data: { formData:formData },

You need to pass the form data object itself, not a plain object.

data: formData


Related Topics



Leave a reply



Submit