Skip to content

Instantly share code, notes, and snippets.

@shwoodard
Created July 3, 2009 18:48
Show Gist options
  • Save shwoodard/140258 to your computer and use it in GitHub Desktop.
Save shwoodard/140258 to your computer and use it in GitHub Desktop.
(function ($) {
$.extend(jQuery ,{
// keep the old one
_ajax: jQuery.ajax,
ajax: function (options) {
var cloneOptions = $.extend({}, options);
this._ajax($.extend(options, {
complete: function (res, status) {
$(document).trigger('ajaxcomplete', arguments);
if (cloneOptions.complete) {cloneOptions.complete.apply(this, arguments);}
},
success: function (data, textStatus) {
$(document).trigger('ajaxsuccess', arguments);
if(cloneOptions.success) {cloneOptions.success.apply(this, arguments);}
},
error: function(xhr, textStatus, errorThrown) {
$(document).trigger('ajaxfailure', arguments);
if (xhr.status === 401) {
window.location.href = JSON.parse(xhr.responseText).redirect_url + "?back=" + window.location.href;
} else {
if(cloneOptions.failure) {cloneOptions.failure.apply(this, arguments);}
}
}
}));
}
});
/*
Post a form via ajax.
options:
type - {String} responseType, ex: html, json, xml, etc
beforeSumbit {Function} executed before submit
@args - void
@scope - the form
@return - {Boolean} true to proceed with submit, false otherwise
events:
form.post.complete - fires after form post complete
@args - resp
*/
$.fn.ajaxPostForm = function (options) {
return $(this).each(function () {
var el = $(this);
var settings = $.extend({
type: 'json',
beforeSubmit: function() {return true;}
}, options);
$(this).submit(function (evt) {
evt.preventDefault();
if (!settings.beforeSubmit.call(el)) {
return;
}
$.post(el.attr('action'), el.serialize(), function(resp) {
$(el).trigger('form.post.complete', arguments);
}, settings.type);
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment