DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

HTTPRequest //JavaScript Class

08.18.2006
| 17891 views |
  • submit to reddit
        <a href="http://jsfromhell.com/classes/http-request">
Class to make remote requests, which can be used on the popular "AJAX".

[UPDATED CODE AND HELP CAN BE FOUND HERE]</a>


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/classes/http-request [v1.0]

HTTPRequest = function(){};
with({$: HTTPRequest.prototype}){
	$.isSupported = function(){
		return !!this.getConnection();
	};
	$.events = ["start", "open", "send", "load", "end"];
	$.filter = encodeURIComponent;
	$.getConnection = function(){
		var i, o = [function(){return new ActiveXObject("Msxml2.XMLHTTP");},
		function(){return new ActiveXObject("Microsoft.XMLHTTP");},
		function(){return new XMLHttpRequest;}];
		for(i = o.length; i--;) try{return o[i]();} catch(e){}
		return null;
	};
	$.formatParams = function(params){
		var i, r = [];
		for(i in params) r[r.length] = i + "=" + (this.filter ? this.filter(params[i]) : params[i]);
		return r.join("&");
	};
	$.get = function(url, params, handler, waitResponse){
		return this.request("GET", url + (url.indexOf("?") + 1 ? "&" : "?") + this.formatParams(params), null, handler, null, waitResponse);
	};
	$.post = function(url, params, handler, waitResponse){
		return this.request("POST", url, params = this.formatParams(params), handler, {
			"Connection": "close",
			"Content-Length": params.length,
			"Method": "POST " + url + " HTTP/1.1",
			"Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
		}, waitResponse);
	};
	$.request = function(method, url, params, handler, headers, waitResponse){
		var i, o = this.getConnection(), f = handler instanceof Function;
		try{
			o.open(method, url, !waitResponse);
			waitResponse || (o.onreadystatechange = function(){
				var s = $.events[o.readyState];
				f ? handler(o) : s in handler && handler[s](o);
			});
			o.setRequestHeader("HTTP_USER_AGENT", "XMLHttpRequest");
			for(i in headers)
				o.setRequestHeader(i, headers[i]);
			o.send(params);
			waitResponse && (f ? handler(o) : handler["end"] && handler["end"](o));
			return true;
		}
		catch(e){
			return false;
		}
	};
}

Example

<fieldset>
	<legend>HTTPRequest example</legend>
	<input type="button" value="POST request with generic listener and params passage" onclick="genericHandler()" />
	<br /><input type="button" value="GET request with specific listener (binded on load and end)" onclick="specificHandler()" />

<script type="text/javascript">
//<![CDATA[

var r = new HTTPRequest;

function myHandler(o){
	alert("Current event = " + r.events[o.readyState] +
	"\nAvailable \"responseText.length\" = " + o.responseText.length);
}
function genericHandler(){
	r.post(location.href, {param: "abcde", name: "Jonas", site: "http://jsfromhell.com"}, myHandler);
}
function specificHandler(){
	r.get(location.href, null, {"load": myHandler, "end": myHandler});
}
document.write(
	"<br />Supports XMLHTTPRequest = ".bold() + r.isSupported(),
	"<br />Encoded with the default filter (\"encodeURIComponent\") = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"})
);

r.filter = escape;
document.write("<br />Encoded with \"escape\" filter = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"}));

r.filter = null;
document.write("<br />Encoded with no filtering = ".bold() + r.formatParams({nameA: "aeiou", nameB: "áéíóú"}));

//]]>
</script>
</fieldset>