Return to Snippet

Revision: 41243
at February 14, 2011 22:38 by freelancephp


Initial Code
/*!
 * SimpleAJAX
 *
 * Simple ajax object for creating ajax calls.
 *
 * Why use SimpleAjax?
 * - Very small, only 2kb minified
 * - Make a asynchrone or synchrone ajax call ( AJAX / SJAX )
 * - Use quick methods get() and post() for GET and POST calls
 * - Use load() method for loading html content and set to given element
 * - Set general settings that will be used by default for every ajax call
 *
 * @version   0.1
 * @author    Victor Villaverde Laan
 * @link      http://www.freelancephp.net/simpleajax-small-ajax-javascript-object/
 * @license   MIT license
 */
var SimpleAJAX = Ajax = {

	xhr: null, // {XMLHttpRequest|ActiveXObject}

	/**
	 * Default ajax settings
	 */
	settings: {
		url: '',
		type: 'GET',
		async: true,
		cache: true,
		data: null,
		contentType: 'application/x-www-form-urlencoded',
		success: null,
		error: null,
		complete: null
	},

	/**
	 * Ajax call
	 * @param {object} options Optional, overwrite the default settings, see ajaxSettings
	 * @return {this} For chaining
	 */
	call: function( options ) {
		var self = this,
			xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject( 'Microsoft.XMLHTTP' ),
			opts = (function ( s, o ) {
				var opts = {};

				for ( var key in s )
					opts[ key ] = ( typeof o[ key ] == 'undefined' ) ? s[ key ] : o[ key ];

				return opts;
			})( this.settings, options ),
			ready = function () {
				if( xhr.readyState == 4 ){
					if ( xhr.status == 200 ) {
						if ( self.isFunction( opts.success ) )
							opts.success.call( opts, xhr.responseText, xhr.status, xhr );
					} else {
						if ( self.isFunction( opts.error ) )
							opts.error.call( opts, xhr, xhr.status );
					}

					if ( self.isFunction( opts.complete ) )
						opts.complete.call( opts, xhr, xhr.status );
				}
			};

		this.xhr = xhr;

		// prepare options
		if ( ! opts.cache )
			opts.url += (( opts.url.indexOf( '?' ) > -1 ) ? '&' : '?' ) + '_nocache='+ ( new Date() ).getTime();

		if ( opts.data ) {
			if ( opts.type == 'GET' ) {
				opts.url += (( opts.url.indexOf( '?' ) > -1 ) ? '&' : '?' ) + this.param( opts.data );
				opts.data = null;
			} else {
				opts.data = this.param( opts.data );
			}
		}

		// set request
		xhr.open( opts.type, opts.url, opts.async );
		xhr.setRequestHeader( 'Content-type', opts.contentType );

		if ( opts.async ) {
			xhr.onreadystatechange = ready;
			xhr.send( opts.data );
		} else {
			xhr.send( opts.data );
			ready();
		}

		return this;
	},

	/**
	 * Ajax GET request
	 * @param {string} url
	 * @param {string|object} data Containing GET values
	 * @param {function} success Callback when request was succesfull
	 * @return {this} For chaining
	 */
	get: function( url, data, success ) {
		if ( this.isFunction( data ) ) {
			success = data;
			data = null;
		}

		return this.call({
			url: url,
			type: 'GET',
			data: data,
			success: success
		});
	},

	/**
	 * Ajax POST request
	 * @param {string} url
	 * @param {string|object} data Containing post values
	 * @param {function} success Callback when request was succesfull
	 * @return {this} For chaining
	 */
	post: function ( url, data, success ) {
		if ( this.isFunction( data ) ) {
			success = data;
			data = null;
		}

		return this.call({
			url: url,
			type: 'POST',
			data: data,
			success: success
		});
	},

	/**
	 * Set content loaded by an ajax call
	 * @param {DOM node|string} el Can contain an element or the id of the element
	 * @param {string} url The url of the ajax call ( include GET vars in querystring )
	 * @param {string} data Optional, the POST data, when set method will be set to POST
	 * @param {function} complete ptional, callback when loading is completed
	 * @return {this} For chaining
	 */
	load: function ( el, url, data, complete ) {
		if ( typeof el == 'string' )
			el = document.getElementById( el );

		this.call({
			url: url,
			type: data ? 'POST' : 'GET',
			data: data || null,
			complete: complete || null,
			success: function ( html ) {
				try {
					el.innerHTML = html;
				} catch( e ) {
					var ph = document.createElement( 'div' );
					ph.innerHTML = html;

					// empty element content
					while ( el.firstChild )
						el.removeChild( el.firstChild );

					// set new html content
					for( var x = 0, max = ph.childNodes.length; x < max; x++ )
						el.appendChild(  ph.childNodes[ x ] );
				}
			}
		});

		return this;
	},


	/**
	 * Make querystring outof object or array of values
	 * @param {object|array} o Keys/values
	 * @return {string} The querystring
	 */
	param: function ( o ) {
		var s = [];

		for ( var key in o ){
			s.push( encodeURIComponent( key ) +'='+ encodeURIComponent( o[ key ] ) );
		}

		return s.join( '&' );
	},

	/**
	 * Check if argument is function
	 * @param {mixed} o
	 * @return {boolean}
	 */
	isFunction: function ( o ) {
		return ( o && o.constructor && o.constructor.toString().indexOf( 'Function' ) !== -1 );
	}

};

Initial URL
http://www.freelancephp.net/simpleajax-small-ajax-javascript-object/

Initial Description
Simple ajax object for creating ajax calls.

Why use SimpleAjax?
 - Very small, only 2kb minified
 - Make a asynchrone or synchrone ajax call ( AJAX / SJAX )
 - Use quick methods get() and post() for GET and POST calls
 - Use load() method for loading html content and set to given element
 - Set general settings that will be used by default for every ajax call

Initial Title
SimpleAjax Object

Initial Tags
ajax, js, object

Initial Language
JavaScript