Quantcast
Viewing latest article 6
Browse Latest Browse All 10

jQuery AJAX Page Template

Whenever I make an AJAX powered page, my jQuery skeleton looks pretty much the same.  I have a load function, bind some event handlers and usually make an AJAX request or two.  I got tired of typing the same stuff out all the time so I created a pretty slick template.  Here’s what I’m starting off with now.

The Code

/**
 * jQuery AJAX File Template
 * @author New Leaf Web Solutions
 * @version 1.0
 */

jQuery(document).ready(function($){
	/**
	 * Perform Initial Load Tasks
	 */
	function onLoad() {
		// Do stuff
	}

	/**
	 * A Click Event Handler Script
	 */
	function myClickEventHandler() {
		/**
		 * Sample AJAX Call
		 */
		var mydata = $('#myajaxform').serialize();
		$.ajax({
			url: "myurl.php",
			async: true,
			cache: true,
			type: "POST",
			data: mydata,
			beforeSend: function(jqXHR, settings) {

			},
			error: function(jqXHR, textStatus, errorThrown) {

			},
			success: function(data, textStatus, jqXHR) {

			},
			complete: function(jqXHR, textStatus) {

			}
		});
	}

	
	/**
	 * A Change Event Handler Script
	 */
	function myChangeEventHandler() {
		// Do stuff
	}

	/**
	 * Bind Events
	 */
	$('.myclickelement').click(function(){
		myClickEventHandler();
	});

	$('.mychangeelement').change(function(){
		myChangeEventHandler();
	});

	// Run the initial load event
	onLoad();
});

Explanation

The idea here is simple.  Bind all the events and create functions for their processing.  You might ask… “Why not just the code directly inside the event handler?”.  Great question.  The reason is because using this method the code becomes more modular.  Almost every time I write jQuery I run into the situation where I have to write similar code for multiple event handlers.  That being said, this method sets you up for easy refactoring.  Not to mention it keeps the code looking super clean and makes everything easy to find.


Viewing latest article 6
Browse Latest Browse All 10

Trending Articles