vinnizworld
4/6/2012 - 10:24 AM

js: Send / Receive data using ajax

js: Send / Receive data using ajax

var ajax = function( url, data, cb){

	var prep = '', method = /fun/.test(typeof data) ? 'GET' : 'POST';
	cb = method === 'GET' ? data : cb;

	// Creating XMLHttp Request Object
	xhr = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");

	//Actions on State Change
	xhr.onreadystatechange = function(){
		if( xhr.readyState >= 4 && xhr.status == 200){ cb(xhr.responseText) }
	}

	if( method == 'POST' && /obj/.test(typeof data)){
		for( var i in data){
			prep += i + '=' + encodeURIComponent(data[i]) + '&';
		}
		prep = prep.slice(0,-1);
	}

	xhr.open(method, url, true);
	xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	xhr.send(prep);
}	

/*
   Usage: For GET Requests | ajax( url , cb );
   ajax( 'url/of/document.html' , function(data){ box.innerHTML = data; } );

   Usage: For POST Requests | ajax( url , data_object , cb );
   obj = {name:'vinay', tech: 'javascript'};
   ajax('post.php',obj,function(data){ msg.innerHTML = data })
*/
var ajax = function(a,b,c){var d="",e=/fun/.test(typeof b)?"GET":"POST",c="GET"===e?b:c;xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");xhr.onreadystatechange=function(){4<=xhr.readyState&&200==xhr.status&&c(xhr.responseText)};if("POST"==e&&/obj/.test(typeof b)){for(var f in b)d+=f+"="+encodeURIComponent(b[f])+"&";d=d.slice(0,-1)}xhr.open(e,a,!0);xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");xhr.send(d);