I created this about a month ago for my ‘Designing for Server Side Languages’ class. I’ve always been a big fan of using jQuery, as it makes everything 10x simpler, but I think I enjoy writing plain old Javascript more. It also cuts down on load time quite a bit, as the jQuery.js file is getting bigger and bigger. The other requirement for the class project was that we had to use a lot of AJAX.
Now I don’t know how many people have actually used a library-less AJAX call, but it’s a good chunk of code. A simple HTTP Request that alerts a response runs about 20 lines of code. Since my application for class was going to have multiple AJAX calls on each page, I needed to add an AJAX method to my core.js file. After a couple of hours I got it perfected and it works flawlessly in Firefox, Safari, and IE7+ (haven’t checked any others). Here’s the code:
Core.ajax = function(method,variables,action,respFunct,respType)
{
try
{
var requester = new XMLHttpRequest();
} catch (error)
{
try
{
var requester = new ActiveXObject("Microsoft.XMLHTTP");
} catch (error)
{
var requester = null;
}
}
if (requester == null)
{
alert('epic fail');
} else
{
requester.onreadystatechange = function()
{
if (requester.readyState == 4)
{
if (requester.status == 200 || requester.status == 304)
{
if(respType == 'XML')
{
var resp = requester.responseXML.documentElement;
}else
{
var resp = requester.responseText;
}
respFunct(resp);
} else
{
alert('epic fail');
}
}
}
var openVars = "";
for(i in variables)
{
openVars = openVars + i + "=" + variables[i] + "&";
}
var temp = openVars.lastIndexOf("&");
openVars = openVars.slice(0,temp);
if(method == "GET")
{
reqOpen = "GET",action + "?" + openVars,true;
requester.open("GET",action + "?" + openVars,true);
requester.send(null);
}else
{
requester.open("POST",action,true);
var header = "Content-type","application/x-www-form-urlencoded";
requester.setRequestHeader(header);
requester.send(openVars);
}
}
}
The method passes 5 parameters:
- Method: The method of data being sent (GET or POST)
- Variables: An associative array of the data being sent
- Action: PHP file that will process the request
- Response Function: Function to be called when a successful response is returned from the PHP file (passes the response as a parameter)
- Response Type: Determines whether the response will be in XML format or simple text (XML or false)
Here is an example of how you could call the AJAX method:
var vars = {
first : 'James',
last : 'Wilson',
location : 'Dallas'
}
Core.ajax("POST",vars,"ajax_process.php",Site.sortResponse,"XML");
Site.sortResponse = function(resp)
{
alert(resp);
}
Any thoughts would be much appreciated!