payal arora payal arora - 4 months ago 65
jQuery Question

Formdata is empty

i am trying to send some jpg files using jquery but the formdata comes empty

here is the html

<input id="fileUpload" multiple="multiple" type="file"/>
<ul>
<li><div id="image-holder"></div></li>
<li><input type="submit" value="Next"></li>
</ul>


here is the script

<script type="text/javascript">
    $('#submit').click(function() {

var files = $("[type='file']")[0].files;

var formdata = new FormData();

$.each(files, function(key, value)
{
console.log(value)
formdata.append('file-'+key, value);
console.log(formdata)
});

$.ajax({
type: "POST",
data: { 'formdata' : formdata , csrfmiddlewaretoken:'{{csrf_token}}'},
url : "{% url 'data_entry' %}",
cache: false,
contentType: false,
processData: false,
success: function(data) {
},
error: function(response, error) {
}
});
});
</script>


this is what i get when i console the formdata
FormData {}
why is the formdata empty?

Answer

FormData object should not be empty. You can use FormData.get() to retrieve value stored at named key within FormData object. Note also #submit element does not appear at html; if you are trying to select <input type="submit"> element, you can use selector $("input[type=submit]").click(handler)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="fileUpload" multiple="multiple" type="file" />
<ul>
  <li>
    <div id="image-holder"></div>
  </li>
  <li>
    <input type="submit" value="Next">
  </li>
</ul>
<script type="text/javascript">
  $("input[type=submit]").click(function() {

    var files = $("[type='file']")[0].files;

    var formdata = new FormData();

    $.each(files, function(key, value) {
      formdata.append("file-" + key, value);
      console.log(formdata.get("file-" + key))
    });

  });
</script>

Comments