In my project, all forms are similar to each other, so I want to write one click function to run all.
Following code works fine except files. File value outputs as undefined. How can I attach file to this form data?
Here’s my click function:
$("#save_form").click(
function(event){
event.preventDefault();
var formData = {};
$('.form-value').each(function() {
var id = $(this).attr('id');
var value;
if ($(this).is('select')) {
value = $(this).find('option:selected').val();
} else if ($(this).is(':file')) {
value = $(this)[0].files[0].value; // Returns undefined.
} else {
value = $(this).val();
}
formData[id] = value;
});
console.log(formData);
When I use without value:
value = $(this)[0].files[0]
I get:
Uncaught TypeError: Illegal invocation
2
Answers
With the help of David and Unmitigated, I solved the issue.
I send file, not the value.
And than, I added two lines to ajax (processData and contentType as false)
Just use the file itself. Files do not have a
value
property.To send the
FormData
withjQuery.ajax
, add the optionsprocessData: false
andcontentType: false
to prevent jQuery from trying to convert theFormData
.