Last active
August 29, 2015 14:08
-
-
Save MadaraUchiha/331f0473c23237b233fd to your computer and use it in GitHub Desktop.
ajaxFormSubmit.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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