View Full Version : My Ajax Class

08-08-2010, 07:53 PM
Hey guys :)

Lately I've been working on a javascript class to make my days working with AJAX requests more delightful. I'm not personally a big fan of frameworks like jquery or prototype as I like to build stuff from the ground and I like to have full control on all my data.

My object seems to work just great, except that it seems to stop working from time to time and I have a feeling that's because Im sending multiple requests at once and it doesnt have a way to deal with multiple requests.

What I would like to implent in my code is a way to deal with multiple request calls and a way to automatically abort an ajax request after a given time (30 seconds for instance).

Oh, and all other suggestions are more than welcome as well! Here's the code I have:

function AjaxRequest(url, method, callback, params) {

var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : ((window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : null);
if (request == null) return;

var parameters = params != null ? arrayToURL(params, method) : null;
var URL = method == 'GET' ? url + parameters : url;

request.open(method, URL, true)

if (method == 'POST') request.setRequestHeader('Content-type','application/x-www-form-urlencoded');

request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
if(request.responseText != null) callback(request.responseText);

function arrayToURL(params, method) {
var urlStr = method == 'GET' ? '?' : '';
for (var param in params) urlStr += param + '=' + params[param] + '&';
return urlStr;

You can easily create an AJAX object with it using the following line of code:

request = new AjaxRequest('ajax/test.php', 'POST', onSucccess, params = {value: 1});