form serialize javascript (no framework)
Here is pure JavaScript approach:
var form = document.querySelector('form');var data = new FormData(form);var req = new XMLHttpRequest();req.send(data);
Though it seems to be working only for POST requests.
For modern browsers only
If you target browsers that support the URLSearchParams
API (most recent browsers) and FormData(formElement)
constructor (most recent browsers), use this:
new URLSearchParams(new FormData(formElement)).toString()
Everywhere except IE
For browsers that support URLSearchParams
but not the FormData(formElement)
constructor, use this FormData polyfill and this code (works everywhere except IE):
new URLSearchParams(Array.from(new FormData(formElement))).toString()
Example
Compatible with IE 10
For even older browsers (e.g. IE 10), use the FormData polyfill, an Array.from
polyfill if necessary and this code:
Array.from( new FormData(formElement), e => e.map(encodeURIComponent).join('=')).join('&')
The miniature from-serialize library doesn't rely on a framework. Other than something like that, you'll need to implement the serialization function yourself. (though at a weight of 1.2 kilobytes, why not use it?)