1 /**
  2  * Ajax
  3  *
  4  * Module for making ajax requests
  5  */
  6 (function (){
  7 
  8 	"use strict";
  9 	
 10 	// Don't bother even defining the object if the XMLHttpRequest isn't available
 11 	if(typeof window.XMLHttpRequest === "undefined")
 12 	{
 13 		return;
 14 	}
 15 
 16 	var ajax = {
 17 		_do: function (url, data, callback, isPost)
 18 		{
 19 			var type, 
 20 				request = new XMLHttpRequest();
 21 		
 22 			if (typeof callback === "undefined")
 23 			{
 24 				/**
 25 				 * @private
 26 				 */
 27 				callback = function (){};
 28 			}
 29 
 30 			type = (isPost) ? "POST" : "GET";
 31 
 32 			url += (type === "GET") ? "?"+this._serialize(data) : '';
 33 			
 34 			request.open(type, url);
 35 
 36 			request.onreadystatechange = function ()
 37 			{
 38 				if (request.readyState === 4)
 39 				{
 40 					callback(request.responseText);
 41 				}
 42 			};
 43 
 44 			if (type === "POST")
 45 			{
 46 				request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 47 				request.send(this._serialize(data));
 48 			}
 49 			else
 50 			{
 51 				request.send(null);
 52 			}
 53 		},
 54 		_serialize: function (data)
 55 		{
 56 			var name,
 57 				value,
 58 				pairs = [];
 59 
 60 			for (name in data)
 61 			{
 62 				if (!data.hasOwnProperty(name))
 63 				{
 64 					continue;
 65 				}
 66 				if (typeof data[name] === "function")
 67 				{
 68 					continue;
 69 				}
 70 
 71 				value = data[name].toString();
 72 
 73 				name = encodeURIComponent(name);
 74 				value = encodeURIComponent(value);
 75 
 76 				pairs.push(name + "=" + value);
 77 			}
 78 
 79 			return pairs.join("&");
 80 		}
 81 	};
 82 
 83 	/**
 84 	 * Sends a GET type ajax request
 85 	 * 
 86 	 * @name get
 87 	 * @function
 88 	 * @memberOf $_
 89 	 * @param string url
 90 	 * @param object data
 91 	 * @param function callback
 92 	 * @return void
 93 	 */
 94 	$_.ext('get', function (url, data, callback){
 95 		ajax._do(url, data, callback, false);
 96 	});
 97 	
 98 	/**
 99 	 * Sends a POST type ajax request
100 	 * 
101 	 * @name post
102 	 * @function
103 	 * @memberOf $_
104 	 * @param string url
105 	 * @param object data
106 	 * @param function callback
107 	 * @return void
108 	 */
109 	$_.ext('post', function (url, data, callback){
110 		ajax._do(url, data, callback, true);
111 	});
112 }());