Created
December 29, 2016 15:23
-
-
Save tincho/055dd4492df33e35134c12aec35b49d7 to your computer and use it in GitHub Desktop.
intercept form and submit it via ajax (requires jQuery)
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
function _noop() {} | |
function _constant(v) { return function() { return v; }; } | |
/** | |
* intercept <form> and submit it via XHR | |
* @param {String} formSelector | |
* @param {Function} successCallback | |
* @param {Function} errorCallback | |
* @param {Function} beforeSubmit | |
*/ | |
function AjaxSubmit(formSelector) { | |
var successCallback = arguments[1] || _noop; | |
var errorCallback = arguments[2] || _noop; | |
var beforeSubmit = arguments[3] || _constant(true); | |
$(document).on('submit', formSelector, { | |
onSuccess: successCallback, | |
onError: errorCallback | |
}, onSubmit); | |
function onSubmit(evt) { | |
evt.preventDefault(); | |
if (! beforeSubmit.call(this) ) return false; | |
var $form = $(this); | |
$.ajax({ | |
type: $form.attr('method'), | |
url: $form.attr('action'), | |
data: $form.serialize(), | |
success: evt.data.onSuccess.bind(this), | |
error: evt.data.onError.bind(this) | |
}); | |
// to stop propagation | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment