Reputation: 9037
I'm trying to put the selected file from the input file to the newly created 'formData' on form submit, below is what I have tried.
first I have the form
<form action="/upload.php">
<fieldset>
<input type="file" name="file">
<input type="text" name="full_name">
</fieldset>
<button>SEND</button>
</form>
and then the script
$(document).ready(function(){
$("form").submit(function(e){
e.preventDefault();
var dis = $(this),fdata = new FormData();
fdata.append('file',dis.find('input[type="file"]').files[0]);
fdata.append('full_name',dis.find('input[name="full_name"]').val());
});
});
but it gives me this error
Uncaught TypeError: Cannot read property '0' of undefined
Any help, ideas please?
Upvotes: 0
Views: 65
Reputation: 133403
Since dis.find('input[type="file"]')
returns jQuery object and they don't have files
property thus you are getting the error, You need to get the underlying DOM element then access the property. So use
dis.find('input[type="file"]')[0].files[0]
instead of
dis.find('input[type="file"]').files[0]
Upvotes: 1
Reputation: 32354
FormData accepts as input the form element
Try the following
fdata = new FormData($(this)[0]);
remove the append
Upvotes: 1