sending FormData with jquery does not work in Safari < 11

Submitting form data with upload fields is made very easy with formdata. Of course, that means some older browsers will not support it. In this case, it was Safari. There was no feasible error message, the targeted php file just wouldn’t stop loading. The ajax request looked like this:

data = new FormData($('#theForm')[0]);
data.append('action', 'action_name_for_wordpress_ajax');

$.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    cache: false,
    data: data,
    processData: false,
    contentType: false,
    success: function(res){
        if(res.success){
            alert("success");
        }
    },
    error: function(res){
        console.log("error"+res.responseText);
    }
});

Turns out that Safari cannot handle such a request when upload fields are empty. Which results in the following workaround: before submitting the form, empty fields have to be removed from the form:

data = new FormData($('#theForm')[0]);
//more data manipulation...

//special case: safari doesnt like this type of subbmitting data if file fields are empty.
$('input[type="file"]').each( function(key, item){
    if($(item).val() == ""){
        data.delete($(item).attr('id'));
    }
});

//now submit the ajax request

data.delete works well here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.