Last Updated: February 25, 2016
·
2.387K
· mroseboom

AJAX requests for forms with files (no iframe)

A simple and effective way to submit forms using FormData object asynchronously. Handles uploading files without the use of an iframe. Nice.

Browser compatibility:
Chrome 7+
Firefox (Gecko) 4.0 (2.0)
Internet Explorer 10+
Opera 12+
Safari 5+

# CoffeeScript
form = document.getElementById 'form'
method = form.getAttribute('method') or 'POST'
action = form.getAttribute('action') or 'foobar.html'
formData = new FormData form
xhr = new XMLHttpRequest
xhr.open method, action, true
xhr.send formData

Background info on FormData:
https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData#Browser_compatibility
https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects