Last Updated: February 25, 2016
·
2.646K
· 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

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside