Last active
August 29, 2015 14:05
-
-
Save mtranter/e83e6779c06178aca3f9 to your computer and use it in GitHub Desktop.
Ajax send a form. Takes into account the HTML5 formaction, formmethod and formenctype attributes.
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($) { | |
var events = ['success', 'error', 'complete']; | |
function getTrigger() { | |
return $(document.activeElement).is('input:submit,button:submit') ? document.activeElement : null; | |
} | |
function capitaliseFirstLetter(string) { | |
return string.charAt(0).toUpperCase() + string.slice(1); | |
} | |
function evalFuncName(fn){ | |
var func = window; | |
var tokens = fn.split('.'); | |
for (var i = 0; i < tokens.length; i++) { | |
func = func[tokens[i]]; | |
}; | |
return func; | |
} | |
function getSubmitOptions(form, target) { | |
function getValOrFallback(formProp) { | |
var targetProp = 'form' + capitaliseFirstLetter(formProp); | |
return target ? (target[targetProp] || form[formProp]) : form[formProp]; | |
} | |
var url = getValOrFallback('action'); | |
var type = getValOrFallback('method'); | |
var contentType = getValOrFallback('enctype'); | |
return { | |
url: url || '/', | |
type: type || 'GET', | |
contentType: contentType || 'application/x-www-form-urlencoded; charset=UTF-8' | |
}; | |
} | |
var api = { | |
ajaxSubmit: function() { | |
return $(this).filter('form').each(function(_, f) { | |
var that = this; | |
var trigger = getTrigger(); | |
var sendOpts = getSubmitOptions(this, trigger); | |
$.each(events, function(_, e) { | |
var fn = $(that).dataAttr(e); | |
sendOpts[e] = fn ? evalFuncName(fn) : $.noop; | |
}); | |
sendOpts.data = $(that).serialize(); | |
var ev = new $.Event('ajaxsubmit'); | |
$(that).trigger(ev); | |
$.ajax(sendOpts); | |
}) | |
} | |
} | |
//jQuery extensions | |
$.fn.dataAttr = function() { | |
var name = 'data-' + arguments[0]; | |
var args = Array.prototype.splice.apply(arguments, [0, 1, name]); | |
return $.fn.attr.apply(this, arguments); | |
} | |
$.fn.ajaxSubmit = api.ajaxSubmit; | |
// Wire up on doc ready | |
$(function(){ | |
$('body').on('submit', 'form[data-ajaxify="true"]', function(e){ | |
e.preventDefault(); | |
api.ajaxSubmit.apply(this, arguments); | |
}); | |
}) | |
})(jQuery) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment