SimpleAjax Object


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. /*!
  2.  * SimpleAJAX
  3.  *
  4.  * Simple ajax object for creating ajax calls.
  5.  *
  6.  * Why use SimpleAjax?
  7.  * - Very small, only 2kb minified
  8.  * - Make a asynchrone or synchrone ajax call ( AJAX / SJAX )
  9.  * - Use quick methods get() and post() for GET and POST calls
  10.  * - Use load() method for loading html content and set to given element
  11.  * - Set general settings that will be used by default for every ajax call
  12.  *
  13.  * @version 0.1
  14.  * @author Victor Villaverde Laan
  15.  * @link http://www.freelancephp.net/simpleajax-small-ajax-javascript-object/
  16.  * @license MIT license
  17.  */
  18. var SimpleAJAX = Ajax = {
  19.  
  20. xhr: null, // {XMLHttpRequest|ActiveXObject}
  21.  
  22. /**
  23. * Default ajax settings
  24. */
  25. settings: {
  26. url: '',
  27. type: 'GET',
  28. async: true,
  29. cache: true,
  30. data: null,
  31. contentType: 'application/x-www-form-urlencoded',
  32. success: null,
  33. error: null,
  34. complete: null
  35. },
  36.  
  37. /**
  38. * Ajax call
  39. * @param {object} options Optional, overwrite the default settings, see ajaxSettings
  40. * @return {this} For chaining
  41. */
  42. call: function( options ) {
  43. var self = this,
  44. xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject( 'Microsoft.XMLHTTP' ),
  45. opts = (function ( s, o ) {
  46. var opts = {};
  47.  
  48. for ( var key in s )
  49. opts[ key ] = ( typeof o[ key ] == 'undefined' ) ? s[ key ] : o[ key ];
  50.  
  51. return opts;
  52. })( this.settings, options ),
  53. ready = function () {
  54. if( xhr.readyState == 4 ){
  55. if ( xhr.status == 200 ) {
  56. if ( self.isFunction( opts.success ) )
  57. opts.success.call( opts, xhr.responseText, xhr.status, xhr );
  58. } else {
  59. if ( self.isFunction( opts.error ) )
  60. opts.error.call( opts, xhr, xhr.status );
  61. }
  62.  
  63. if ( self.isFunction( opts.complete ) )
  64. opts.complete.call( opts, xhr, xhr.status );
  65. }
  66. };
  67.  
  68. this.xhr = xhr;
  69.  
  70. // prepare options
  71. if ( ! opts.cache )
  72. opts.url += (( opts.url.indexOf( '?' ) > -1 ) ? '&' : '?' ) + '_nocache='+ ( new Date() ).getTime();
  73.  
  74. if ( opts.data ) {
  75. if ( opts.type == 'GET' ) {
  76. opts.url += (( opts.url.indexOf( '?' ) > -1 ) ? '&' : '?' ) + this.param( opts.data );
  77. opts.data = null;
  78. } else {
  79. opts.data = this.param( opts.data );
  80. }
  81. }
  82.  
  83. // set request
  84. xhr.open( opts.type, opts.url, opts.async );
  85. xhr.setRequestHeader( 'Content-type', opts.contentType );
  86.  
  87. if ( opts.async ) {
  88. xhr.onreadystatechange = ready;
  89. xhr.send( opts.data );
  90. } else {
  91. xhr.send( opts.data );
  92. ready();
  93. }
  94.  
  95. return this;
  96. },
  97.  
  98. /**
  99. * Ajax GET request
  100. * @param {string} url
  101. * @param {string|object} data Containing GET values
  102. * @param {function} success Callback when request was succesfull
  103. * @return {this} For chaining
  104. */
  105. get: function( url, data, success ) {
  106. if ( this.isFunction( data ) ) {
  107. success = data;
  108. data = null;
  109. }
  110.  
  111. return this.call({
  112. url: url,
  113. type: 'GET',
  114. data: data,
  115. success: success
  116. });
  117. },
  118.  
  119. /**
  120. * Ajax POST request
  121. * @param {string} url
  122. * @param {string|object} data Containing post values
  123. * @param {function} success Callback when request was succesfull
  124. * @return {this} For chaining
  125. */
  126. post: function ( url, data, success ) {
  127. if ( this.isFunction( data ) ) {
  128. success = data;
  129. data = null;
  130. }
  131.  
  132. return this.call({
  133. url: url,
  134. type: 'POST',
  135. data: data,
  136. success: success
  137. });
  138. },
  139.  
  140. /**
  141. * Set content loaded by an ajax call
  142. * @param {DOM node|string} el Can contain an element or the id of the element
  143. * @param {string} url The url of the ajax call ( include GET vars in querystring )
  144. * @param {string} data Optional, the POST data, when set method will be set to POST
  145. * @param {function} complete ptional, callback when loading is completed
  146. * @return {this} For chaining
  147. */
  148. load: function ( el, url, data, complete ) {
  149. if ( typeof el == 'string' )
  150. el = document.getElementById( el );
  151.  
  152. this.call({
  153. url: url,
  154. type: data ? 'POST' : 'GET',
  155. data: data || null,
  156. complete: complete || null,
  157. success: function ( html ) {
  158. try {
  159. el.innerHTML = html;
  160. } catch( e ) {
  161. var ph = document.createElement( 'div' );
  162. ph.innerHTML = html;
  163.  
  164. // empty element content
  165. while ( el.firstChild )
  166. el.removeChild( el.firstChild );
  167.  
  168. // set new html content
  169. for( var x = 0, max = ph.childNodes.length; x < max; x++ )
  170. el.appendChild( ph.childNodes[ x ] );
  171. }
  172. }
  173. });
  174.  
  175. return this;
  176. },
  177.  
  178.  
  179. /**
  180. * Make querystring outof object or array of values
  181. * @param {object|array} o Keys/values
  182. * @return {string} The querystring
  183. */
  184. param: function ( o ) {
  185. var s = [];
  186.  
  187. for ( var key in o ){
  188. s.push( encodeURIComponent( key ) +'='+ encodeURIComponent( o[ key ] ) );
  189. }
  190.  
  191. return s.join( '&' );
  192. },
  193.  
  194. /**
  195. * Check if argument is function
  196. * @param {mixed} o
  197. * @return {boolean}
  198. */
  199. isFunction: function ( o ) {
  200. return ( o && o.constructor && o.constructor.toString().indexOf( 'Function' ) !== -1 );
  201. }
  202.  
  203. };

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.