JAVASCRIPT: Smart, unobtrusive AJAX form submission with jQuery
A former coworker was telling me recently about MooTools and how the AJAX functions are so easy to use. He sent me the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | function attachedToOnSubmitOfAForm(){ sp = $("someForm"); sp.addClass('loader'); sp.send({ onComplete: function(json) { .... }, onFailure:function(){ .... } }); } |
Great concept, right? No need to tell it where to send the data or what fields to send, since the form already contains that info. It’s mostly unobtrusive, so any browser that doesn’t have JS enabled would still be able to submit.
So my immediate response was, “Very cool. I’m sure a jQuery plugin either exists or could be created pretty easily to handle that.”
I built the following plugin in maybe 30 minutes, and had it tested in another 15.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | (function(jQuery) { jQuery.fn.send = function(options) { return this.each(function(){ var form = jQuery(this); jQuery(this).bind('submit', function() { jQuery.ajax(jQuery.extend({ type : form.attr('method') || 'get', url : form.attr('action') || window.location.href, data : form.serialize() }, options)); return false; }); }); }; })(jQuery); |
There are some of you that are wondering, “Why is this necessary? I can write my own jQuery.ajax() code every time.” Yep, and that’s part the problem I’m trying to solve. The plugin is a shortcut for most of the jQuery.ajax() code you’d normally write and it makes unobtrusive form submission dead simple:
1 2 3 4 5 | jQuery(function(){ jQuery('form').send({ complete : function(data) { alert(data.responseText); } }); }); |
The function takes one parameter, an object that extends the jQuery.ajax method.
Here’s a demo and the download.
2008-09-23: Updated window.location to window.location.href (Thanks Samori)
Please don’t use window.location when you meant window.location.href, this is not part of any standard and who knows, maybe tomorrow window.location.toString will return window.host…
I know that sounds stupid but it’s always good to avoid programming by accident.
The plugin is nicely written tough, really smart.