How to inspect FormData?

form-data, javascript

Solution

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);

Problem

I've tried `console.log` and looping through it using `for in`. Here it the MDN Reference on FormData. Both attempts are in this fiddle. ``` var fd = new FormData(), key; // poulate with dummy data fd.append("key1", "alskdjflasj"); fd.append("key2", "alskdjflasj"); // does not do anything useful console.log(fd); // does not do anything useful for(key in fd) { console.log(key); } ``` How can I inspect form data to see what keys have been set.

Original source

Related problems