Created
June 28, 2017 19:14
-
-
Save tincho/59dd4fd92e7490f084cfcc89e1bc5de3 to your computer and use it in GitHub Desktop.
simple jquery snippet to override a native form's with an ajax call
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
// requires jQuery! | |
const noop = () => {}; | |
const constant = v => () => v; | |
const beTrue = constant(true); // () => true; | |
function $Ajaxify(form, ...callbacks) { | |
if (typeof callbacks[0] === 'object') { | |
var { | |
onSuccess = noop, onError = noop, beforeSend = beTrue | |
} = callbacks[0]; | |
} else { | |
var [onSuccess = noop, onError = noop, beforeSend = beTrue] = callbacks; | |
} | |
jQuery(document).on('submit', form, { | |
onSuccess, | |
onError | |
}, function onSubmit(evt) { | |
console.log("im onsubmit"); | |
evt.preventDefault(); | |
evt.stopImmediatePropagation(); | |
evt.stopPropagation(); | |
if (!beforeSend.apply(this, ...arguments)) return false; | |
var $form = jQuery(this); | |
jQuery.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; | |
}); | |
} |
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
// usage example | |
$Ajaxify("#someForm", { | |
beforeSend: function() { | |
// if beforeSend returns false, submit is prevented | |
}, | |
onSuccess: function() { | |
}, | |
onError: function() { | |
} | |
}); | |
// also allows: | |
$Ajaxify("#myForm", () => "i'm onsubmit", () => "i'm onerror", () => "i'm beforeSend"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment