14-12-2010

jQuery minimalist ajax form plugin

The following jQuery plugin allows you to handle forms submits via ajax rather than via page (re) loading. Havent built in support for checkboxes and radio yet but that shouldn't be too hard if needed.

(function($) {//jq plugin
	$.fn.simpleAjaxForm = function(options) {
		var defaults = {};
		if (typeof (options === 'function')) defaults['callback'] = options;
		var opts = $.extend({}, defaults, options);
		return this.each(function(i) {
			$(this).submit(function(e){
				var submitvalues = {},submitit = true;
				$(this).find('input[type=text],input[type=hidden],input[type=password],textarea,select,input[type=password]').removeClass('error').each(function(){
					var $this = $(this); 				
					if ($this.hasClass('required') && $.trim($this.val()) === ''){
						if (submitit) submitit = false;
						$this.addClass('error');					
					}else{	
						submitvalues[this.name] = $this.val();
					}
				})
				if (submitit){
					$.post((this.action||''),submitvalues,function(resp){
						if (opts.callback && typeof(opts.callback) ==='function') opts.callback(resp);
					});
				}
				return false;
			})
 
	    	});	
	};
})(jQuery);
 

now you can:

$('#box_submit_form').simpleAjaxForm(function(resp){
	alert(resp)	
});
 

Comments:

Your comment:

»

 

[x]