376

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.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98

24 Answers24

509

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);
Community
  • 1
  • 1
Ryan Endacott
  • 8,772
  • 4
  • 27
  • 39
  • 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. –  Jun 16 '13 at 16:29
  • 2
    recent versions of chrome and firefox now provide an iterator: `myFormData.entries()` – rloth Jun 29 '16 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! – Ryan Endacott Jul 25 '16 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. – Peter Valadez Aug 16 '16 at 02:04
  • For iterating `FormData` in IE/Edge: https://stackoverflow.com/questions/37938955/iterating-through-formdata-in-ie – cs_pupil Oct 30 '18 at 17:15
  • The 'for' loop in this answer to appear in the console is a life saver and big lesson for developing faster and more accurate. – KJS Mar 01 '21 at 00:20
  • 2
    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. – Maciej Krawczyk Feb 18 '22 at 10:30
222

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)
danronmoon
  • 3,814
  • 5
  • 34
  • 56
Endless
  • 34,080
  • 13
  • 108
  • 131
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.

John
  • 1
  • 13
  • 98
  • 177
Ghost Echo
  • 1,997
  • 4
  • 31
  • 46
  • 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 '16 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. – Johnny Welker Apr 15 '16 at 16:23
  • 1
    ES6: `for (const pair of formData.entries()) { console.log(pair[0], pair[1]); }` – 2540625 Sep 02 '16 at 00:02
  • **for ... of** is `ES6` feature and it will work only in certain browsers. Excluding any version of IE [according to MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/for...of#Browser_compatibility) – Zanshin13 May 27 '17 at 12:03
  • for of is not supported in most IE. only supported in IE edge – mingca Mar 20 '18 at 13:14
  • six years have past and I'm here to say that @2540625 comment is missing a `}`, it should be `for (const pair of formData.entries()) { console.log(pair[0], pair[1])};` – Edu Ruiz Apr 14 '23 at 21:35
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}`);
}
Hooray Im Helping
  • 5,194
  • 4
  • 30
  • 43
  • Can you define what `formData` exactly is – AlxVallejo Oct 29 '20 at 19:06
  • Check out https://developer.mozilla.org/en-US/docs/Web/API/FormData – agm1984 Oct 31 '20 at 03:59
  • multipart/form-data matches your `
    ` part. It is generally for when you upload files. FormData allows you to maintain your own payload object in JavaScript--separately from the HTML
    component. This allows you to decouple it and perform more advanced form management logic.
    – agm1984 Oct 31 '20 at 04: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

Gurkan Yesilyurt
  • 2,635
  • 2
  • 20
  • 21
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)
     });

Asifali
  • 207
  • 3
  • 10
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.

Luc
  • 194
  • 2
  • 4
  • 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. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols – Triynko Nov 15 '16 at 14:25
8

You can use Array.from()

console.log(Array.from(formData.entries()))
Mustafa Burak Kalkan
  • 1,132
  • 21
  • 28
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
AminRostami
  • 2,585
  • 3
  • 29
  • 45
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>
kaiser
  • 21,817
  • 17
  • 90
  • 110
3

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

formData.forEach(entries => console.log(entries));
Yousuf
  • 760
  • 1
  • 5
  • 13
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)])

ngr
  • 139
  • 2
  • 10
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

2540625
  • 11,022
  • 8
  • 52
  • 58
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) {


            },

       });
}
sparsh turkane
  • 1,165
  • 12
  • 13
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.

P.M
  • 2,880
  • 3
  • 43
  • 53
silkyland
  • 67
  • 8
  • 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'` – Lovethenakedgun Mar 07 '19 at 13:28
1

Try this function:

function formDataToObject(formData) {
  return Array.from(formData.entries()).reduce((old, pair) => ({
    ...old,
    [pair[0]]: pair[1],
  }), {});
}
Mauro
  • 41
  • 1
  • 6
  • 3
    While this code snippet may be the solution, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-‌​code-based-answers) 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 '19 at 15:49
  • sorter version: `Object.fromEntries(fd)` – Endless Nov 29 '20 at 14:01
1

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

MD SHAYON
  • 7,001
  • 45
  • 38
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)})
debugger
  • 1,442
  • 1
  • 9
  • 14
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);
    })
Praveen RL
  • 588
  • 9
  • 13
  • Please [don't post identical answers to questions](https://meta.stackexchange.com/q/104227). 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 06 '22 at 13:41
1

Simplified Answer:

//prints formData (both keys and values)
 console.log([...formData.entries()])
 
//Answer to OG question...prints only keys
    console.log([...fd.keys()]) 
Mr.Pacific
  • 61
  • 4
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)
Luca C.
  • 11,714
  • 1
  • 86
  • 77
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

Eduardo Lucio
  • 1,771
  • 2
  • 25
  • 43
0

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

Shumon Pal
  • 314
  • 3
  • 12
-1
console.log(myformdata.get("mykey");

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

console.log(myformdata.getall());