Skip to content

Instantly share code, notes, and snippets.

@avand
Created June 4, 2014 21:27
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 avand/b454e980da8442cfdc3b to your computer and use it in GitHub Desktop.
Save avand/b454e980da8442cfdc3b to your computer and use it in GitHub Desktop.
HTMLFormElement.prototype.submitViaXHR = function(success, error) {
if (this.classList.contains("submitting")) return;
var xhr = new XMLHttpRequest(),
form = this,
readyStates = ["unsent", "opened", "headers-received", "loading", "done"];
form.classList.add("submitting");
form.classList.remove("errored");
form.removeAttribute("data-ready-state");
xhr.addEventListener("readystatechange", function() {
form.setAttribute("data-ready-state", readyStates[xhr.readyState]);
if (xhr.readyState == 4) {
form.classList.remove("submitting");
switch (xhr.status) {
case 200:
success(xhr);
break;
default:
form.classList.add("errored");
error(xhr);
}
}
});
xhr.open(form.getAttribute("method"), form.getAttribute("action"));
xhr.send(new FormData(form));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment