Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

jQuery Ajax plugin for form submits and links

Sunday, September 2nd, 2012 by Servage

jQuery offers many cool things, but sometimes you like to take the functionality and suit it just a little better or make it just a little more specific to what you need. For example AJAX calls is something which could be standardzied accross your website or app. Why write the same jQuery code all over, of you could create a plugin you attach to every element you want to have the AJAX functionality like this:

$('form').MyAjax();

This attaches the MyAjax plugin to all your forms, for example.

The code below is suitable for forms and links:

function MyAjax (el, options){
	var t = this;
	t.el = el;
	t.$el = $(el);

	t.defaultOptions = {
		url: '/',
		type: "GET",
		data: {},
		dataType: "json",
		callback: null,
	};		

	t.init = function(){
		t.options = $.extend({},t.defaultOptions, options);

		if (t.el.tagName == 'A') {
			t.$el.click(function(event) {
				event.preventDefault();
				t.options.url = t.$el.attr('href');
				t.sendRequest();
			});
		}
		else if (t.el.tagName == 'FORM') {
			t.$el.submit(function(event) {
				event.preventDefault();
				t.options.url = t.$el.attr('action');
				t.options.type = 'POST';
				t.options.data = t.$el.serialize();
				t.sendRequest();
			});
		}
	};

	t.sendRequest = function() {
		$.ajax({
			type: t.options.type,
			url: t.options.url,
			data: t.options.data,
			dataType: 'json',
			success: function(response, textStatus, XMLHttpRequest) {
				// Do things with the response
			},
			complete: function(XMLHttpRequest, textStatus) {
				// Write debug info to console
				console.log(XMLHttpRequest);
			},
		});
	}

	// Run initializer
	t.init();
};

(function($){
	$.fn.MyAjax = function(options) {
		return this.each(function(){
			(new MyAjax(this, options));
		});
	};
})(jQuery);

The above is not a completely working version for your site, since it doesn’t do anything with the return. But you can add the things you want to happen there. The basics are that the plugin takes a form or a link, identifies data and targets, and sends the AJAX response. For debugging purposes the console.log() method is used to output the request object.

jQuery Ajax plugin for form submits and links, 5.0 out of 5 based on 3 ratings
Categories: Tips & Tricks

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.