I submit a form manually via jQuery. I use FormData with all input elements from this form. See code below:
$("#submit-form").on('submit', function (event) {
event.preventDefault();
var form = $('#submit-form')[0];
var data = new FormData(form);
$.ajax({
type: "POST",
url: "my-best-handler",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 60000
});
});
One of input elements is file and it's optional to set it. When it's not set, I don't need to use it in FormData and be sent with other elements to request handler. The problem is that currently it will be sent even if it's not set.
I'm curious how I can exclude it from FormData if it's not set.
In worst case I can create FormData manually like here.
But I hope there is "black list" like approach by removing just not set file from FormData OR any other elegant way.
Update: I came with the following solution:
if (!$("#input-file").val()) {
data.delete('input-file');
}
You can use the delete()
function to remove your field
var form = $('#submit-form')[0];
var data = new FormData(form);
if (!$("#input-file").val()) {
data.delete('input-file');
}