118

Can you tell me whats wrong with this:

var formdata = new FormData();
formdata.append("key", "value");
console.log(formdata);

My output looks like this, I cant find my "key" - "value" pair

FormData
*__proto__: FormData
**append: function append() { [native code] }
***arguments: null
***caller: null
***length: 0
***name: "append"
***prototype: append
***__proto__: function Empty() {}
*constructor: function FormData() { [native code] }
**arguments: null
**caller: null
**length: 0
**name: "FormData"
**prototype: FormData
**toString: function toString() { [native code] }
*__proto__: Object
**__proto__: Object
**__defineGetter__: function __defineGetter__() { [native code] }
**__defineSetter__: function __defineSetter__() { [native code] }
**__lookupGetter__: function __lookupGetter__() { [native code] }
**__lookupSetter__: function __lookupSetter__() { [native code] }
**constructor: function Object() { [native code] }
**hasOwnProperty: function hasOwnProperty() { [native code] }
**isPrototypeOf: function isPrototypeOf() { [native code] }
**propertyIsEnumerable: function propertyIsEnumerable() { [native code] }
**toLocaleString: function toLocaleString() { [native code] }
**toString: function toString() { [native code] }
**valueOf: function valueOf() { [native code] }

I can't understand! Yesterday it worked so well, and today my head crashed the keyboard so many times! Firefox, Chrome, both the same :/

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
netzaffin
  • 1,602
  • 3
  • 13
  • 14

8 Answers8

139

New in Chrome 50+ and Firefox 39+ (resp. 44+):

  • formdata.entries() (combine with Array.from() for debugability)
  • formdata.get(key)
  • and more very useful methods

Original answer:

What I usually do to 'debug' a FormData object, is just send it (anywhere!) and check the browser logs (eg. Chrome devtools' Network tab).

You don't need a/the same Ajax framework. You don't need any details. Just send it:

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

Easy.

Sha
  • 152
  • 3
  • 8
Rudie
  • 52,220
  • 42
  • 131
  • 173
  • thanks - this was a useful quick way to get the FormData object by typing it into the Chrome console. – Dan Smart Apr 20 '13 at 13:08
  • [According to Google](https://developers.google.com/web/updates/2016/03/formdata-methods-for-inspection-and-modification?hl=en) formData methods were added in Chrome v50. – thdoan Jun 01 '16 at 08:35
  • How would you look at the browser logs if its a mobile browser like Safari? I am using the FormData object in a web app meant for mobile and can't figure out how to debug it. – kiwicomb123 Dec 29 '16 at 22:50
  • 1
    @kiwicomb123 `Formdata.entries()` + `Array.from()` + `alert()` if it's modern enough, or look into [mobile debugging](https://webdesign.tutsplus.com/articles/quick-tip-using-web-inspector-to-debug-mobile-safari--webdesign-8787) – Rudie Dec 30 '16 at 08:14
  • so no edge or ie11? – SuperUberDuper Jan 07 '17 at 22:46
  • Was curious about the plain/pure-js answer! – Pysis May 22 '19 at 15:06
50

You say it's not working. What are you expecting to happen?

There's no way of getting the data out of a FormData object; it's just intended for you to use to send data along with an XMLHttpRequest object (for the send method).

Update almost five years later: In some newer browsers, this is no longer true and you can now see the data provided to FormData in addition to just stuffing data into it. See the accepted answer for more info.

Community
  • 1
  • 1
Jesper
  • 7,477
  • 4
  • 40
  • 57
  • 23
    OK... this sucks. Why can I not log the FormData in my console? :-( This just makes no sense to me, since i thought it is an common object – netzaffin Oct 13 '11 at 11:19
  • 12
    @netzaffin: Both Firebug and Chrome's inspector let you see the sent request parameters in an XHR request as long as you've opened the network tab and started logging, so you should be able to get by on that. You could also make a wrapper object that logs the fields and appends to the FormData, and then check that for the values (not forgetting to send the inner FormData instead of the wrapper object). – Jesper Oct 13 '11 at 11:27
  • 1
    At least, can I check if `formdata` object has a file inside? – MarceloBarbosa Feb 11 '15 at 16:59
  • 1
    @MarceloBarbosa: It doesn't seem like you can get any information out of it. You'll just have to keep this information yourself. – Jesper Feb 12 '15 at 09:38
  • As pointed out by @Jesper you can check the XHR request sent in the network tab tab of Developer tools , there is Params option there which even lets you see the content of POST request sent. Also the response. – Anirudh Mar 31 '16 at 09:20
  • @netzaffin if you want a common object, then you can [loop through the entries](https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries) in formData to build your object. Keep in mind the minimum browser requirements though. – thdoan Jun 01 '16 at 08:41
  • Yes there is: `Array.from(new FormData(event.target));` will give you a 2d array of key value pairs. – mlunoe Sep 29 '16 at 05:44
30

You might have been having the same problem I was initially having. I was trying to use FormData to grab all my input files to upload an image, but at the same time I wanted to append a session ID to the information passed along to the server. All this time, I thought by appending the information, you would be able to see it in the server by accessing the object. I was wrong. When you append to FormData, the way to check the appended information on the server is by a simple $_POST['*your appended data*'] query. like so:

js:

$('form').submit(function(){
    var sessionID = 8;
    var formData = new FormData(this);
    formData.append('id', sessionID);

    $.ajax({
        url: "yoururl.php",
        data: formData,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function(data){
            alert(data);
        }
    });
});

then on php:

$sessionID = $_POST['id'];
$files = $_FILES['image'];

$foreach ($files as $key=>val){
    //...
}
CodeGodie
  • 12,116
  • 6
  • 37
  • 66
17

If you are in Chrome you can check the Post Data

Here is How to check the Post data

  1. Go to Network Tab
  2. Look for the Link to which you are sending Post Data
  3. Click on it
  4. In the Headers, you can check Request Payload to check the post data

Chrome's DevTools

Spooky
  • 2,966
  • 8
  • 27
  • 41
madhu131313
  • 7,003
  • 7
  • 40
  • 53
12

form data doesn't appear in web browser console

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

try this way it will show

Dulanga Heshan
  • 1,335
  • 1
  • 19
  • 36
8

you can see it you need to use console.log(formData.getAll('your key')); watch the https://developer.mozilla.org/en-US/docs/Web/API/FormData/getAll

Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62
yehonatan yehezkel
  • 1,116
  • 18
  • 28
3

In my case on Edge browser:

  const formData = new FormData(this.form);
  for (const [key, value] of formData.entries()) {
      formObject[key] = value;
  }

give me the same error

So I'm not using FormData and i just manually build an object

import React from 'react';    
import formDataToObject from 'form-data-to-object';

  ...

let formObject = {};

// EDGE compatibility -  replace FormData by
for (let i = 0; i < this.form.length; i++) {
  if (this.form[i].name) {
    formObject[this.form[i].name] = this.form[i].value;
  }
}

const data = formDataToObject.toObj(formObject): // convert "user[email]":"customer@mail.com" => "user":{"email":"customer@mail.com"}

const orderRes = await fetch(`/api/orders`, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      });

const order = await orderRes.json();
2

React Version

Make sure to have a header with 'content-type': 'multipart/form-data'

_handleSubmit(e) {
    e.preventDefault();
    const formData = new FormData();
          formData.append('file', this.state.file);
    const config = {
      headers: {
        'content-type': 'multipart/form-data'
      }
    }

     axios.post("/upload", formData, config)
         .then((resp) => {
             console.log(resp)
         }).catch((error) => {
    })
  }

  _handleImageChange(e) {
    e.preventDefault();
    let file = e.target.files[0];
    this.setState({
      file: file
    });
  }

View

  #html
 <input className="form-control"
    type="file" 
    onChange={(e)=>this._handleImageChange(e)} 
 />
7urkm3n
  • 6,054
  • 4
  • 29
  • 46