Skip to content

Instantly share code, notes, and snippets.

@ypresto
Last active September 6, 2018 13:47
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ypresto/cabce63b1f4ab57247e1f836668a00a5 to your computer and use it in GitHub Desktop.
Save ypresto/cabce63b1f4ab57247e1f836668a00a5 to your computer and use it in GitHub Desktop.
iOS 11.3 Safari / macOS Safari 11.1 empty <input type="file"> XHR bug workaround for rails-ujs / jquery_ujs
// iOS 11.3 Safari / macOS Safari 11.1 empty <input type="file"> XHR bug workaround.
// This should work with every modern browser which supports ES5 (including IE9).
// https://stackoverflow.com/questions/49614091/safari-11-1-ajax-xhr-form-submission-fails-when-inputtype-file-is-empty
// https://github.com/rails/rails/issues/32440
document.addEventListener('ajax:before', function(e) {
var inputs = e.target.querySelectorAll('input[type="file"]:not([disabled])')
inputs.forEach(function(input) {
if (input.files.length > 0) return
input.setAttribute('data-safari-temp-disabled', 'true')
input.setAttribute('disabled', '')
})
})
// You should call this by yourself when you aborted an ajax request by stopping a event in ajax:before hook.
document.addEventListener('ajax:beforeSend', function(e) {
var inputs = e.target.querySelectorAll('input[type="file"][data-safari-temp-disabled]')
inputs.forEach(function(input) {
input.removeAttribute('data-safari-temp-disabled')
input.removeAttribute('disabled')
})
})
@bojanst
Copy link

bojanst commented Jul 17, 2018

i owe you a big one for this solution, and a beer !!!
Thanks!

@musa11971
Copy link

Such a stupid bug. We fixed this by removing all empty file inputs before submitting...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment