<< back to code examples

easyAjax jQuery Plugin

easyAjax is a JQuery plugin that I created to simplify the use of Ajax content and make a smaller footprint when developing with Ajax. It extends the JQuery .ajax() method. It alows you to reuse the same ajax request as many times as you need to and lets you set different perameters for each instance of the plugin call. All this can be done with as little as 1 line of code.

/* 
Jquery Plugin
Plugin Name: Easy Ajax
Author: Craig Bauer
Ver: 1.0
License: MIT
*/
(function($) {

	$.fn.easyAjax = function(options) {

		// Default Settings
		var settings = $.extend({

			href : 'default.html',
			linkColor : 'red',
			slideSpeed : 100,
			timeOut : 20000,
			cursor : 'pointer',

		}, options );

		return this.each(function(){

			$(this)
			.css('color', settings.linkColor)
			.css('cursor', settings.cursor);

			var object = $(this);
			
			var content = $('<div id="wrap"><div id="content"></div></div>');
			content.prependTo('body');

			object.on('click', loadEasyAjax);

			function loadEasyAjax(event){

				event.preventDefault();		

				$.ajax('jquery.easyAjax/ajaxPages/' + settings.href, {
					success: function(response) {
						$('#wrap').fadeIn(200);
						$('#content').html(response).slideDown( settings.slideSpeed );
					},
					error : function(request, errorType, errorMessage){
						alert('Error: ' + errorType + ' with message: ' + errorMessage);
					},
					timeout : settings.timeOut,
					complete : function() { 
						var closeBtn = $('<div class="closeBtn">x</div>');
						var wrap = $('#wrap');
						closeBtn.appendTo('#content');
						closeBtn.on('click', function() {

							$('#content').slideUp( settings.slideSpeed, function(){
								$('#wrap').fadeOut(200);
							});
							
						})
					},
		
				}); //close .ajax

			} // close loadEasyAjax Function
			
		}); //close return

	}

} (jQuery) );//close wrapped function

implementation and options

<script>

	$(document).ready(function() {

		// Loads the default template
		$('.default').easyAjax();
				
		// Loads a custom template called signup.html
		$('.signup').easyAjax({
			href: 'signup.html',
		});

		// Loads a custom template called moreInfo.html with more options
		$('.moreInfo').easyAjax({
			href: 'x.html',
			linkColor : 'blue',
			cursor : 'crosshair',
			slideSpeed : 800,
		});

	});

</script>

html markup

       <a href="#" class="signup">Click here to signup!</a>
       <a href="#" class="moreInfo">Click here for more info.</a>

More Code Projects