3

Trying to load a form into a FormData object, but it just creates an empty FormData instead, i can alert the form object (displaying HTMLFORMOBJECT) and if i remove e.preventDefault it will pair the name/values into the url but the FormData doesn't work. I have even tried to create dummy forms with hidden inputs but they don't load into a FormData

JAVASCRIPT

$('#create-element-form').submit(function(e) {
    e.preventDefault();
    var formdata = new FormData(document.getElementById('create-element-form'));
    alert(formdata.get('name'));
});

HTML

<form id="create-element-form">
    <div class="form-group">
        <input type="text" class="form-control" name="name" placeholder="Element Name" maxlength="100" required/>
    </div>
    <div class="form-group">
        <input type="text" class="form-control text-number-input" name="backups" placeholder="Number of backups for element" maxlength="100" required/>
    </div>
    <button type="submit" class="btn btn-default btn-lg btn-block">Create Element</button>
</form>

It Just alerts

undefined

I feel like its probably something simple i am missing

1 Answers1

8

formdata is not a plain object. It doesn't have any properties that could be serialized. You have to use the object's methods to access the contained data. For example:

console.log(formdata.get('name'));

See the MDN documentation.

The primary use case for FormData objects is to be sent via XMLHTTPRequest.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Was going to post this. OP, You probably want something like http://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery – Sergio Nov 26 '15 at 22:53
  • I am using the formdata in a jquery ajax request, and even if i remove the stringify and use .get it comes out as undefined... –  Nov 27 '15 at 01:09
  • @Hooner: It works fine for me: http://jsfiddle.net/nqm9x461/. However, `.get` [seems to be supported only in Firefox and Opera atm](https://developer.mozilla.org/en-US/docs/Web/API/FormData/get#Browser_compatibility). If you are using jQuery anyway, then I suggest to use jQuery's own method for serializing the form data: http://api.jquery.com/serializeArray/ . – Felix Kling Nov 27 '15 at 01:26
  • 'supported only in firefox and opera' *has been using chrome entire time* ty felix –  Nov 27 '15 at 01:38