Anurag Singh
Anurag Singh

Reputation: 727

Form data displays null object

I have made a simple form and want to post the data using the jQuery function new FormData(). To me every thing seems to be good but when I am displaying the variable data in console.log, then I get FormData { append=append()} as output.

My code is:

<form action="" enctype="multipart/form-data" method="post" name="edit_user" id="edit_user">
   <input type="text" name="Fname" >
   <input type="file" name="image">
   <input type="submit" value="submit">
</form>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        $('#edit_user').submit(function(event) {
            event.preventDefault();
            var formdata = new FormData(this);
            console.log(formdata);
       });

Upvotes: 1

Views: 16601

Answers (2)

Jatin Bansal
Jatin Bansal

Reputation: 181

You can get the data by using get function of FormData like this:

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

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 238075

Your code (included below) works fine. This is how FormData is supposed to work. The data can be posted using XHR or $.ajax (see this question for tying it to jQuery), but it is not serialised into a string for you. It is only converted into the appropriate format when the XHR request is made.

There is no way to see the data in a FormData object in the console without making the XHR request.

$(document).ready(function() {
  $('#edit_user').submit(function(event) {
    event.preventDefault();
    //enter code here
    var formdata = new FormData(this);

    console.log(formdata);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" enctype="multipart/form-data" method="post" name="edit_user" id="edit_user">
  <input type="text" name="Fname">
  <input type="file" name="image">
  <input type="submit" value="submit">
</form>

Upvotes: 3

Related Questions