392

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.

4
  • Isn't it a firefox only feature? Jun 12, 2013 at 13:38
  • 2
    caniuse.com/#search=FormData
    – user1637281
    Jun 12, 2013 at 13:43
  • 2
    You want to do key of fd instead of key in fd. I don't know why this is technically yet, but it works. Documentation here.
    – cilphex
    May 26, 2016 at 21:21
  • So, there's no chrome or firefox plugin to show form data without adding any code to your javascript? Jan 30, 2019 at 20:51

24 Answers 24

527

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);
7
  • Well, that would be a good idea, I would wrap FormData in a helper method and then pass in the object literal. Then save it in case you want to look at it later.
    – user1637281
    Jun 16, 2013 at 16:29
  • 2
    recent versions of chrome and firefox now provide an iterator: myFormData.entries()
    – rloth
    Jun 29, 2016 at 13:40
  • 1
    At the time of writing, there was no way to access FormData. I've now updated the answer to reflect the new API. Thanks for the heads up rloth! Jul 25, 2016 at 20:43
  • 2
    I think it's also useful to note that you can grab an existing form's data using: var formData = new FormData(formElement). If you are using JQuery, you can therefore do this: var formData = new FormData($('#formElementID')[0]). Then append data as needed. Aug 16, 2016 at 2:04
  • 3
    Still, this has to be one of the worst browser APIs. Why didn't they just add a method to return to get an object of key / value pairs. Feb 18, 2022 at 10:30
235

Few short answers

[...fd] // shortest devtool solution
Array.from(fd) // Same as above
console.log(...fd) // shortest script solution
console.log([...fd]) // Think 2D array makes it more readable
console.table([...fd]) // could use console.table if you like that
console.log(Object.fromEntries(fd)) // Works if all fields are uniq
console.table(Object.fromEntries(fd)) // another representation in table form
new Response(fd).text().then(console.log) // To see the entire raw body

Longer answer

Others suggest logging each entry of fd.entries(), but the console.log can also take multiple arguments
console.log(foo, bar, ...)
To take any number of argument you could use the apply method and call it as such: console.log.apply(console, array).
But there is a new ES6 way to apply arguments with spread operator and iterator
console.log(...array).

Knowing this, And the fact that FormData and array's both has a Symbol.iterator method in its prototype that specifies the default for...of loop, then you can just spread out the arguments with ...iterable without having to go and call formData.entries() method (since that is the default function) you can just do for (x of formData) if you prefer that

var fd = new FormData()

fd.append('key1', 'value1')
fd.append('key2', 'value2')
fd.append('key2', 'value3')

// using it's default for...of specified by Symbol.iterator
// Same as calling `fd.entries()`
for (let [key, value] of fd) {
  console.log(`${key}: ${value}`)
}

// also using it's default for...of specified by Symbol.iterator    
console.log(...fd)

// Only shows up in devtool (not here in this code snippet)
console.table([...fd])

// Don't work in IE (use last pair if same key is used more)
console.log(Object.fromEntries(fd))

If you would like to inspect what the raw body would look like then you could use the Response constructor (part of fetch API), this will convert your formdata to what it would actually look like when you upload the formdata

var fd = new FormData()

fd.append('key1', 'value1')
fd.append('key2', 'value2')

new Response(fd).text().then(console.log)

10
  • 3
    spread operator!! Excellent and really simple, displays the formdata as psuedo Json format. Thanks - for the New Response, i just get [[PromiseStatus]]:"pending"
    – platinums
    Oct 16, 2017 at 10:55
  • 7
    Or from the web console just write [...fd]
    – Endless
    Oct 16, 2017 at 21:14
  • hells bells - you did it again @Endless. what method is that called using the brackets?
    – platinums
    Nov 10, 2017 at 18:09
  • well, the brackets is just an array and you are creating a new one. You are spreading out the entries with ... from formdata to create the new array with all the items, then the console just dump the result from the last line you wrote
    – Endless
    Nov 10, 2017 at 21:53
  • 2
    best answer here - should remove all the gumpf and just leave the 2nd code snippet - many thanks
    – danday74
    Feb 22, 2018 at 11:24
47

I use the formData.entries() method. I'm not sure about all browser support, but it works fine on Firefox.

Taken from https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries

// 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]); 
}

There is also formData.get() and formData.getAll() with wider browser support, but they only bring up the Values and not the Key. See the link for more info.

6
  • 3
    It's finally easy to look into FormData objects! This worked for me after upgrading to Chrome 50 (released yesterday, 13th of April 2016).
    – jbb
    Apr 14, 2016 at 14:49
  • 3
    var pair of throws errors for me. Replacing it with in seems to print something at least, however its not a key or value like MDN states. Apr 15, 2016 at 16:23
  • 1
    ES6: for (const pair of formData.entries()) { console.log(pair[0], pair[1]); }
    – 2540625
    Sep 2, 2016 at 0:02
  • for ... of is ES6 feature and it will work only in certain browsers. Excluding any version of IE according to MDN
    – Zanshin13
    May 27, 2017 at 12:03
  • for of is not supported in most IE. only supported in IE edge
    – mingca
    Mar 20, 2018 at 13:14
29

ES6+ solutions:

To see the structure of form data:

console.log([...formData])

To see each key-value pair:

for (let [key, value] of formData.entries()) {
  console.log(`${key}: ${value}`);
}
3
  • Can you define what formData exactly is
    – AlxVallejo
    Oct 29, 2020 at 19:06
  • Check out developer.mozilla.org/en-US/docs/Web/API/FormData
    – agm1984
    Oct 31, 2020 at 3:59
  • multipart/form-data matches your <form enctype="multipart/form-data"> part. It is generally for when you upload files. FormData allows you to maintain your own payload object in JavaScript--separately from the HTML <form> component. This allows you to decouple it and perform more advanced form management logic.
    – agm1984
    Oct 31, 2020 at 4:02
20

Angular

var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

formData.forEach((value,key) => {
  console.log(key+" "+value)
});

Not: When I am working on Angular 5 (with TypeScript 2.4.2), I tried as above and it works except a static checking error but also for(var pair of formData.entries()) is not working.

var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

formData.forEach((value,key) => {
  console.log(key+" "+value)
});

Check at Stackblitz

2
  • + not compatible with IE 11 (value, key) => {... A headache !
    – Delphine
    Jan 23, 2018 at 16:01
  • 1
    nice. want to give you 10 star. May 13, 2019 at 15:53
13

Easy Method

I used this code in angular 8

var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');

 formData.forEach((value,key) => {
    console.log(key+value)
     });

10

In certain cases, the use of :

for(var pair of formData.entries(){... 

is impossible.

I've used this code in replacement :

var outputLog = {}, iterator = myFormData.entries(), end = false;
while(end == false) {
   var item = iterator.next();
   if(item.value!=undefined) {
       outputLog[item.value[0]] = item.value[1];
   } else if(item.done==true) {
       end = true;
   }
    }
console.log(outputLog);

It's not a very smart code, but it works...

Hope it's help.

1
  • 1
    I'd flip the if statement so it checks done first. done is the authoritative flag; if done is false or not specified, then value is a valid item (even if it holds the value undefined). When done is present and true, the end of the sequence has been reached, and value doesn't even have to be defined. If value is defined when done is true, then value is interpreted as the return value of the iterator. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – Triynko
    Nov 15, 2016 at 14:25
8

You can use Array.from()

console.log(Array.from(formData.entries()))
2
  • 1
    Even better: console.log(Object.fromEntries(body.entries())) Aug 25, 2021 at 14:11
  • 3
    something even better: console.log(Object.fromEntries(body)) - you don't need the entries() part
    – Endless
    Nov 14, 2021 at 22:59
7

Simplified Answer:

//prints formData (both keys and values)
 console.log([...formData.entries()])
 
//Answer to OG question...prints only keys
    console.log([...fd.keys()]) 
4

in typeScript of angular 6, this code is working for me.

var formData = new FormData();
formData.append('name', 'value1');
formData.append('name', 'value2');
console.log(formData.get('name')); // this is return first element value.

or for all values:

console.log(formData.getAll('name')); // return all values
3

You have to understand that FormData::entries() returns an instance of Iterator.

Take this example form:

<form name="test" id="form-id">
    <label for="name">Name</label>
    <input name="name" id="name" type="text">
    <label for="pass">Password</label>
    <input name="pass" id="pass" type="text">
</form>

and this JS-loop:

<script>
    var it = new FormData( document.getElementById('form-id') ).entries();
    var current = {};
    while ( ! current.done ) {
        current = it.next();
        console.info( current )
    }
</script>
0
3

In angular 7 i got entries on console using below line of code.

formData.forEach(entries => console.log(entries));
3

Already answered but if you want to retrieve values in an easy way from a submitted form you can use the spread operator combined with creating a new Map iterable to get a nice structure.

new Map([...new FormData(form)])

2
  • although - this has a Problem with inp_nam[some_mult][] - only the last is seen
    – halfbit
    Oct 21, 2019 at 3:47
  • There is no need to destruct the object into an array... Map accepts a iterable. new Map(fd)
    – Endless
    Nov 29, 2020 at 14:00
2

Here's a function to log entries of a FormData object to the console as an object.

export const logFormData = (formData) => {
    const entries = formData.entries();
    const result = {};
    let next;
    let pair;
    while ((next = entries.next()) && next.done === false) {
        pair = next.value;
        result[pair[0]] = pair[1];
    }
    console.log(result);
};

MDN doc on .entries()

MDN doc on .next() and .done

1
  • !(next = entries.next()).done is sufficient. There's no need to split it up. Jul 26, 2023 at 15:13
2
  function abc(){ 
    var form = $('#form_name')[0]; 
        var formData = new FormData(form);
        for (var [key, value] of formData.entries()) { 
            console.log(key, value);
        }
        $.ajax({
            type: "POST",
            url: " ",
            data:  formData,
            contentType: false,
            cache: false,
            processData:false,
            beforeSend: function() {

            },
            success: function(data) {


            },

       });
}
1
  • + not compatible with IE 11 for...of... A headache !
    – Delphine
    Jan 23, 2018 at 15:59
2

The MDN suggests the following form:

let formData = new FormData();
formData.append('name', 'Alex Johnson')
for(let keyValuePair of formData.entries()){
    console.log(keyValuePair); //has form ['name','Alex Johnson']
}

Alternatively

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

Consider adding ES+ Polyfills, in case the browser or environment doesn't support latest JavaScript and FormData API.

I hope this helps.

1
  • Did you test this code before running it? formData() should be capitalized, firstly. Also, your for ... of loop in line 3 is implicitly calling FormData.entries, you can see this by running new FormData()[Symbol.iterator] in the console. Finally, if you run this in browsers like Edge, which don't support FormData.entries, you get unexpected results, such as printing the method names available on the FormData object: >>> var data = new FormData(); data.append("Foo", "Bar"); for(let x in data){console.log(x)}; <<< 'append' Mar 7, 2019 at 13:28
2

Form data

var formData = new FormData(); // Currently empty
formData.append('username', 'Chris');

for (var key of formData.keys()) {
   console.log(key);
}

for (var value of formData.values()) {
   console.log(value);
}

know more

1

Try this function:

function formDataToObject(formData) {
  return Array.from(formData.entries()).reduce((old, pair) => ({
    ...old,
    [pair[0]]: pair[1],
  }), {});
}
2
  • 3
    While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Johan
    Mar 13, 2019 at 15:49
  • sorter version: Object.fromEntries(fd)
    – Endless
    Nov 29, 2020 at 14:01
1

If you are using typescript, then you can console FormData like this:

const productData = new FormData();
productData.append('name', name);
productData.append('description', description);
productData.forEach((key,value)=>{
   console.log(key, value)})
1

formData.entries() is throwing error in latest version. So you can try with the following:

formData.forEach((value: FormDataEntryValue, key: string) => {
      console.log(value, key);
    })
1
  • Please don't post identical answers to questions. Post one good answer, then vote/flag to close the other questions. Also don't answer question tagged with only JavaScript with another language such as TypeScript, CoffeeScript or any other
    – Endless
    Dec 6, 2022 at 13:41
1

Easy way to get specific value formData.get('key_name')

0

Map it to an object like this:

let debug_form_data = {}
form_data.forEach((value,key)=> debug_form_data[key]=value)
console.debug(debug_form_data)
1
  • 2
    Same as const debug_form_data = Object.fromEntries(form_data)
    – Endless
    Apr 6, 2021 at 17:11
0

Based on @2540625 answer an ECMAScript 5 compatible version...

// NOTE: Inspect a HTML request data ("FormData"). By Questor
function inspRqstData(rqstData) {
    var dataEntries = rqstData.entries();
    var rqstDataAsJO = {};
    var dataNext;
    var dataPair;
    while ((dataNext = dataEntries.next() || true) && dataNext.done === false) {
        dataPair = dataNext.value;
        console.log(dataPair[0], dataPair[1]);
    }
}

var rqstData = new FormData();
rqstData.append('key1', 'value1');
rqstData.append('key2', 'value2');
inspRqstData(rqstData);

NOTE: The "FormData" could be something that enframe "ECMAScript 5" JavaScript support. This can be inferred by crossing information regarding browser support/compatibility in these references (see IE10)...

https://www.w3schools.com/js/js_es5.asp
https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData#browser_compatibility


EXTRA: Convert a HTML request data ("FormData") to a simple JavaScript Object...

// NOTE: Convert a HTML request data ("FormData") to a JavaScript Object. By Questor
function rqstDataToJO(rqstData) {
    var dataEntries = rqstData.entries();
    var rqstDataAsJO = {};
    var dataNext;
    var dataPair;
    while ((dataNext = dataEntries.next() || true) && dataNext.done === false) {
        dataPair = dataNext.value;
        rqstDataAsJO[dataPair[0]] = dataPair[1];
    }
    return rqstDataAsJO;
}

var rqstData = new FormData();
rqstData.append("key1", "value1");
rqstData.append("key2", "value2");
var rqstDataAsJO = rqstDataToJO(rqstData);
console.log(rqstDataAsJO.key1)
console.log(rqstDataAsJO.key1)

Thanks! =D

Other References...

https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

-1
console.log(myformdata.get("mykey");

i think its the answer! and you can use "getall" like that

console.log(myformdata.getall());
1
  • I'm getting, getall() is not a function Sep 20, 2021 at 13:52