How to inspect FormData?
JavascriptForm DataJavascript Problem Overview
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.
Javascript Solutions
Solution 1 - Javascript
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: https://stackoverflow.com/questions/7752188/formdata-appendkey-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);
Solution 2 - Javascript
Few short answers
[...fd] // shortest devtool solution
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 argumentsconsole.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 iteratorconsole.log(...array)
.
Knowing this, And the fact that FormData and array's both has a Symbol.iterator method in it's 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)
// 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)
Solution 3 - Javascript
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.
Solution 4 - Javascript
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}`);
}
Solution 5 - Javascript
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)
});
Solution 6 - Javascript
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)
});
Solution 7 - Javascript
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.
Solution 8 - Javascript
You can use Array.from()
console.log(Array.from(formData.entries()))
Solution 9 - Javascript
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
Solution 10 - Javascript
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);
};
Solution 11 - Javascript
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>
Solution 12 - Javascript
In angular 7 i got entries on console using below line of code.
formData.forEach(entries => console.log(entries));
Solution 13 - Javascript
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)])
Solution 14 - Javascript
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) {
},
});
}
Solution 15 - Javascript
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.
Solution 16 - Javascript
Try this function:
function formDataToObject(formData) {
return Array.from(formData.entries()).reduce((old, pair) => ({
...old,
[pair[0]]: pair[1],
}), {});
}
Solution 17 - Javascript
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);
}
Solution 18 - Javascript
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)
Solution 19 - Javascript
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
Solution 20 - Javascript
console.log(myformdata.get("mykey");
i think its the answer! and you can use "getall" like that
console.log(myformdata.getall());