Skip to content

Instantly share code, notes, and snippets.

@MadaraUchiha
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MadaraUchiha/331f0473c23237b233fd to your computer and use it in GitHub Desktop.
Save MadaraUchiha/331f0473c23237b233fd to your computer and use it in GitHub Desktop.
ajaxFormSubmit.js
/**
* Takes a form node and sends it over AJAX.
* @param {HTMLFormElement} form - Form node to send
* @param {function} callback - Function to handle onload.
* this variable will be bound correctly.
*/
function ajaxFormSubmit (form, callback) {
var url = form.action,
xhr = new XMLHttpRequest();
//Creates an array from the form's elements. Casts the HTMLCollection.
var params = Array.from(form.elements)
.filter(function(el) {
//Allow only elements that don't have the 'checked' property
//Or those who have it, and it's checked for them.
return typeof(el.checked) === 'undefined' || el.checked;
//Practically, filter out checkboxes/radios which aren't checekd.
})
.map(function(el) {
//Map each field into a name=value string, make sure to properly escape!
return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
}).join('&'); //Then join all the strings by &
xhr.open("POST", url);
xhr.setRequestHeader("Content-type", "application/x-form-urlencoded");
//.bind ensures that this inside of the function is the XHR object.
xhr.onload = callback.bind(xhr);
//All preperations are clear, send the request!
xhr.send(params);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment