Oneupweb : Write a Simple Ajax Library for Javascript!

Everyone has their favorite Ajax library. Weather it be prototype, jQuery, or some lesser known yet equally awesome library that allows you to harness the power of Ajax—it seems you can find these anywhere these days.

In this tutorial, we are going to explore writing our own simple Ajax module using JavaScript.

Setup the module

True to the JavaScript module pattern, we will wrap our little tool up in an anonymous function

(function(){

}).call(this); //"this" will be the window object

Why do we do this? We can easily invoke this function on the global window object, and because we are inside of a function we can gain the benefit of private members, and thus avoid naming conflicts and people accidentally overwriting our methods. Let’s take advantage of this fact by setting up a few private properties and methods for our Ajax module:

(function(){
//the global window object
var root = this,
//our XMLHttp object
http = null,
//a function to get the XMLHttp object
getXmlHttp  = function() {
	if (! http ) http = new XMLHttpRequest;
	return http;
},
//a helper function to build query strings
joinParams = function(params) {
	var str = '';
	for ( var k in params ) {
		str += k + '=' + params[k] + '&';
	};
	return str.replace('/&$/','');
}
}).call(this);

//create our namespace on the global window object
root.Ouw = {};

Add the Ajax singleton

We are going to create a single Ajax singleton to act as our powerhouse for Ajax interaction. We can do this by adding an Ajax property to our module.

Ouw.ajax = {
};

Next we add all the necessary methods to communicate with the server.

Ouw.ajax = {
	request:function(params) {
		var method = params.type,
			url = params.url,
			data = joinParams(params.data),
			success = params.success;

		if ( /get/i.exec(method) ) {
			if ( data ) url = url + '?' + data;
		}
		http = getXmlHttp();
		if ( http ) {
			http.open(method.toUpperCase(),url,true);
			http.onreadystatechange = function() {
				if ( http.readyState == 4 ) {
					if ( http.status == 200 ) {
						success(http.responseText);
					}
				}
			}
		}
		if ( /get/i.exec(method) ) {
			http.send(null);
		} else {
//send the same headers an html form would
			http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			http.setRequestHeader("Content-length", data.length);
			http.setRequestHeader("Connection", "close");
			http.send(data);
		}
	},
        //a wrapper for easy get requests
	get:function(url,fn) {
		this.request({
			type:'get',
			url:url,
			success:fn
		});
	},
        //a wrapper for easy post requests
	post:function(url,data,fn) {
		this.request({
			type:'post',
			url:url,
			data:data,
			success:fn
		});
	}
};

Putting it all together

The source code as a whole:

(function(){
var root = this,
	http = null,
	getXmlHttp  = function() {
		if (! http ) http = new XMLHttpRequest;
		return http;
	},
	joinParams = function(params) {
		var str = '';
		for ( var k in params ) {
			str += k + '=' + params[k] + '&';
		};
		return str.replace('/&$/','');
	}

root.Ouw = {};
Ouw.ajax = {
	request:function(params) {
		var method = params.type,
			url = params.url,
			data = joinParams(params.data),
			success = params.success;

		if ( /get/i.exec(method) ) {
			if ( data ) url = url + '?' + data;
		}
		http = getXmlHttp();
		if ( http ) {
			http.open(method.toUpperCase(),url,true);
			http.onreadystatechange = function() {
				if ( http.readyState == 4 ) {
					if ( http.status == 200 ) {
						success(http.responseText);
					}
				}
			}
		}
		if ( /get/i.exec(method) ) {
			http.send(null);
		} else {
			http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			http.setRequestHeader("Content-length", data.length);
			http.setRequestHeader("Connection", "close");
			http.send(data);
		}
	},
	get:function(url,fn) {
		this.request({
			type:'get',
			url:url,
			success:fn
		});
	},
	post:function(url,data,fn) {
		this.request({
			type:'post',
			url:url,
			data:data,
			success:fn
		});
	}
};

}).call(this);

Using this bad boy is a snap!

Ouw.ajax.get('/blog/test.xml',function(xml){
    alert(xml);
})

//or how about a post request
Ouw.ajax.post('/blog/someaction.php',{one:'two'},function(resp){
    alert(resp);
});

Clean it up and make it your own

It’s up to you to support older versions of IE, and add any kind of fancy functionality to your new module. Happy coding!