3

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');
}
nickolay.laptev
  • 1,230
  • 8
  • 24

2 Answers2

1

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');
}
Nidhin Joseph
  • 8,658
  • 3
  • 18
  • 40
1

Disabling input approach.

Disabled form controls never get submitted

$("#submit-form").on('submit', function (event) {
        event.preventDefault();

        // disable before creating FormData
        $(this).find(':file').prop('disabled', function(){
             return !this.files.length;
        });

        var form = $('#submit-form')[0];
        var data = new FormData(form);

As mentioned in comments should re-enable in ajax success callback

charlietfl
  • 164,229
  • 13
  • 110
  • 143
  • Thanks. I think an approach with delete looks more easy to maintain. Please let me know if you think differently or your approach has advantages over delete one. I updated my question with exact code I will use. – nickolay.laptev Aug 12 '19 at 22:17
  • 1
    Either way should work. The `delete` intent is very easy to read though – charlietfl Aug 12 '19 at 22:19
  • 1
    You should re-enable it after the form submission is done, otherwise the use won't be able to select a file later. – Barmar Aug 12 '19 at 23:39
  • @Barmar right you are...wasn't thinking about re-use – charlietfl Aug 12 '19 at 23:46