This is my first foray into the wild world of jQuery plugin development. The plugin "ajaxifies" forms, which isn't particularly spectacular:
- It gets the basics (action, method) from the form itself, serializes the form's fields, and sends the request.
- Users can provide (via its options) callback functions for the local ajax events (beforeSend, complete, success and error).
- The dataType can also be set from a custom data attribute, which - if present - takes precedence.
Everything seems to be working as expected (repo, with a simple demo). Since this is my first plugin, I'd be particularly interested in critiques of its structure. That said, as always in reviews, any aspect of the code is fair game for criticism.
The plugin code:
(function ($) {
$.fn.ajaxForm = function (options) {
var settings = $.extend({}, $.fn.ajaxForm.defaults, options);
return this.each(function () {
var $form = $(this);
dataType = $form.attr("data-dataType");
if (typeof dataType != "undefined") dataType = settings.dataType;
$form.on("submit", function (event) {
event.preventDefault();
$.ajax({
type: $form.attr("method"),
url: $form.attr("action"),
data: $form.serialize(),
cache: false,
dataType: dataType,
beforeSend: function () {
$form.addClass("ajaxForm-loading");
if (typeof settings.beforeSend == "function") settings.beforeSend.call($form);
},
complete: function () {
$form.removeClass("ajaxForm-loading");
if (typeof settings.complete == "function") settings.complete.call($form);
},
success: function (response) {
if (typeof settings.success == "function") settings.success.call($form, response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (typeof settings.error == "function") settings.error.call($form, XMLHttpRequest, textStatus, errorThrown);
}
});
});
});
};
$.fn.ajaxForm.defaults = {
dataType: "json",
beforeSend: function () {},
complete: function () {},
success: function () {},
error: function () {}
};
})(jQuery);
Initialization:
$(document).ready(function () {
$("form").ajaxForm({
dataType: "html",
success: function (response) {
console.log(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Oops: " + errorThrown);
}
});
});