Andrew
Andrew

Reputation: 2435

Can't build a FormData object out of existing form

I'm trying to build a FormData object out of a form on my page. I'm getting the form element like this:

var form = document.forms['upload_form'];

And then I'm building the FormData object like this:

var fd = new FormData(form);

Since you cannot log values in a FormData object (as described here), I'm sending the formdata to '/' just so I can see its contents in my Network Inspector. The contents of the request payload are simply:

------WebKitFormBoundaryKAgAjii8IMLyJFcB--

and nothing else! If I manually append a value to the form like this:

fd.append("username", "Groucho");

it works:

------WebKitFormBoundaryZikgEBo7sTzvlndC
Content-Disposition: form-data; name="username"

Groucho

I've also tried selecting the form element in other ways, such as with jQuery:

var form = $(".upload_form");
var fd = new FormData(form[0]);

No matter how I select the form element, the form variable certainly does have the form in it (it's not null or empty), but constructing the FormData object with it as a parameter just does not seem to work. Can anyone help?

PS I'm using Chrome 31.0.1650.57. I've also tried this in Safari 7.0 with the same results.

Another thing: The inputs in this form are nested inside a number of divs. Could this be a problem?

Upvotes: 2

Views: 4292

Answers (1)

Andrew
Andrew

Reputation: 2435

This was happening because I didn't have name attributes set on my inputs. Apparently, new FormData() and $.serialize() will ignore any inputs without names.

Upvotes: 3

Related Questions