I've been spending couple of months now building static pages interacting with SodaHead's API for some of our partners (ESPN, Fox...) and I'm always looking to shorten the amount of code on the page. The following is a cross browser compatible micro Ajax library (handeling GET/POST/DELETE...) in just 302 Bytes once minified.
The code
Note that errors are detected from the status of the response starting by 5, like a HTTP500. Modifying the library should be very easy, you might want to add 4xx response too or even give it its own "clientfail" callback (HTTP4xx are considered error on the client side).
/* opts = {
data: "x=1&y=yes",
method: "GET", // default POST
success: function(req){...}, // status 2xx
fail: function(req){...}, // status 5xx
other: function(req){...}, // other status
}
*/
function ajax(url, opts){
var req;
if (window.XMLHttpRequest) req=new XMLHttpRequest();
else req=new ActiveXObject("Microsoft.XMLHTTP");
req.onreadystatechange = function(){
if (req.readyState == 4){
if (/^2/.test(req.status) && opts.success) opts.success(req);
else if (/^5/.test(req.status) && opts.fail) opts.fail(req);
else if (opts.other) opts.other(req);
}
};
req.open(opts.method || 'POST', url, true);
req.send(opts.data);
}
minified
Here is a minified version 302 Bytes
function ajax(e,t,i){i=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),i.onreadystatechange=function(){4==i.readyState&&(/^2/.test(i.status)&&t.success?t.success(i):/^5/.test(i.status)&&t.fail?t.fail(i):t.other&&t.other(i))},i.open(t.method||"POST",e,!0),i.send(t.data)}
example
A call would look like:
ajax("/remote/data/", {
success: function(r){ alert(r.responseText); },
data: "x=1&y=yes"
});