I\'m using jQuery and Ajax for my forms to submit data and files but I\'m not sure how to send both data and files in one form?
I currently do almost the same with b
For me, it didn't work without enctype: 'multipart/form-data'
field in the Ajax request. I hope it helps someone who is stuck in a similar problem.
Even though the enctype
was already set in the form attribute, for some reason, the Ajax request didn't automatically identify the enctype
without explicit declaration (jQuery 3.3.1).
// Tested, this works for me (jQuery 3.3.1)
fileUploadForm.submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
enctype: 'multipart/form-data',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log('Thank God it worked!');
}
}
);
});
// enctype field was set in the form but Ajax request didn't set it by default.
As others mentioned above, please also pay special attention to the contentType
and processData
fields.