FormData.append("key", "value") is not working

JavascriptHtmlForm Data

Javascript Problem Overview


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 :/

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - Javascript

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){
    //...
}

Solution 4 - Javascript

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

Solution 5 - Javascript

> form data doesn't appear in web browser console

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

try this way it will show

Solution 6 - Javascript

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

Solution 7 - Javascript

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]":"[email protected]" => "user":{"email":"[email protected]"}
  
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();

Solution 8 - Javascript

#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 this._handleImageChange(e)} />

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnetzaffinView Question on Stackoverflow
Solution 1 - JavascriptRudieView Answer on Stackoverflow
Solution 2 - JavascriptJesperView Answer on Stackoverflow
Solution 3 - JavascriptCodeGodieView Answer on Stackoverflow
Solution 4 - Javascriptmadhu131313View Answer on Stackoverflow
Solution 5 - JavascriptDulanga HeshanView Answer on Stackoverflow
Solution 6 - Javascriptyehonatan yehezkelView Answer on Stackoverflow
Solution 7 - JavascriptRamadanoski JulieView Answer on Stackoverflow
Solution 8 - Javascript7urkm3nView Answer on Stackoverflow