Too Cool for Internet Explorer

The smallest AJAX framework ever   July 21st, 2009

The most AJAX frameworks are bloated with many functions you’ll never use or need. Who wants 60 KB of JavaScript if your only need is to send and load data? I Don’t.

I have found somewhere a short howto for AJAX, and derived (rewritten) the smallest AJAX framework ever out of it:

var ajax = false;
if(window.XMLHttpRequest) ajax = new XMLHttpRequest();
else if(window.ActiveXObject) {
	try { ajax = new ActiveXObject("Msxml2.XMLHTTP"); }
	catch (e) {
		try { ajax = new ActiveXObject("Microsoft.XMLHTTP"); }
		catch (e) {}
	}
}

function ajaxGetContent(type, url, parameter, output_function) {
	if(!ajax) eval(output_function + '(false);');
	ajax.onreadystatechange = function() {
		if(output_function != 'void' && ajax.readyState == 4) {
			if(ajax.status == 200) eval(output_function + '(ajax.responseText);');
			else eval(output_function + '(false);');
		}
	}
	if(type == "post") {
		ajax.open('POST', url, true);
		ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		ajax.send(parameter);
	} else {
		ajax.open('GET', url + ((parameter.length > 0)?"?":"") + parameter, true);
		ajax.send(null);
	}
}

That’s short, isn’t it?

To get the data you want you have to simply call the function and define a function which will be called after the data arrives:

ajaxGetContent('post', '/myURL/index.php', 'a=b', 'myDataCallBack');

function myDataCallBack(myContent) {
	if(myContent == false) {
		// something went wrong
	} else {
		// have fun with your data
	}
}

And if you want to send data only and don’t care of the answer, use this syntax:

ajaxGetContent('post', '/myURL/index.php', 'a=b', 'void');

Some explanation:
- type = How to send the data (Parameters). “post” or “get”.
- url = Where to send it to.
- parameter = URL-style parameters. Never use a question mark!
- output_function = The function which will be called after the data is received.

This Tool is tested in Opera 9+10, Firefox 2+3 and MSIE 7+8.

Have fun!

Tags: , , , ,
This entry was posted on Tuesday, July 21st, 2009 at 00:41 and is filed under Programming, Tools. You can follow any responses to this entry through the RSS 2.0 feed.You can leave a response, or trackback from your own site.

No Responses

Leave a Reply