Smallest JavaScript AJAX library ever!
I have built the smallest, easiest and fastest JavaScript AJAX library ever. Inspired by moo.ajax, but without the need for prototype or any other external library - the file has 779 bytes without the comments, but with all formatting in place and some pretty long function and variable names. As presented here it only returns the responseText, but you could easily change that to the full XMLHttpRequest object.
Here is how it works:
- create a callback function
- call microAjax:
microAjax("url", callbackfunction) - That's it, your callback function will be called with the response text as parameter
[edited] I have added a new function - you can now add a post Body as last parameter, but it's optional!
Easy? No?
// microAjax by Stefan Lange-Hegermann // this code is in the public domain // you can do with it whatever you want! function microAjax(url, callbackFunction) { this.bindFunction = function (caller, object) { return function() { return caller.apply(object, new Array(object)); } } this.stateChange = function (object) { if (this.request.readyState==4) { this.callbackFunction(this.request.responseText); } } this.getRequest = function() { if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP'); else if (window.XMLHttpRequest) return new XMLHttpRequest(); else return false; } if (arguments[2]) this.postBody = arguments[2]; else this.postBody=""; this.callbackFunction=callbackFunction; this.url=url; this.request = this.getRequest(); if(this.request) { this.request.onreadystatechange = this.bindFunction(this.stateChange, this); if (this.postBody!="") { this.request.open("POST", url, true); this.request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); this.request.setRequestHeader('Connection', 'close'); } else { this.request.open("GET", url, true); } this.request.send(this.postBody); } }by Stefan LH




Even smaller: http://p.caboo.se/52045 only 401 Byte with same api. Thats 49.1% less code
If you just wanna use GET it's 248 Byte = 68.6% smaller
That is cool, but: "with all formatting in place and some pretty long function and variable names"
I referred to that Version: http://www.blackmac.de/uploads/microAjax.js There is the most formatting removed and the names are abbriviated abbreviated. It weights 789 Bytes and can be minified with jsmin (http://javascript.crockford.com/jsmin.html) to 757 Byte.
OK, my fault - you won
Thanks for this wonderful AJAX lib Stefan. Quick question, will this lib also handle file uploads(using input=file)? Appreciate any code snippets if you can. Thanks.