Ajax script

2009-12-23

This is a small Ajax script I use. It amounts to 8k uncompressed, make that 2.5k when minified.

The script is easy to set up using any namespace (by default it uses Ajax) and has two public methods; Ajax.get and Ajax.post.

Usage: Ajax.get(url, callback, options)
Usage: Ajax.post(url, data, callback, options)

Url will be the url fetched with a random string added to it, unless you tell it not to through the options.

For posts, data is an object literal or string. Unless you tell it through options not to, it will convert the object to name=value& pairs. Also, caching is explicitly disabled for posts, unless specified otherwise.

Callback is a function to be called, but only when the requests succeeds. There's currently no crossbrowser way of failure. The callback will be called with one parameter, the contents of the fetched document (through options you can get this as xml).

Options is an object literal through which you can supply certain options:
- boolNoAntiCache: do not append a random number to the url
- boolNoAntiCachePost: do not send anti-cache-headers for posts
- boolReturnXML: call the callback with callback(xml,str) instead of callback(str)
- boolBlocking: block while fetching the document
- boolSurpressDebug: do not use the global "debug" when fetching a document (if you have no "debug" global, this won't make a difference)
- boolNoConvert: post only, send the options as is (should be a name=value& style string

Inside the script, commented, is also a script loading function I used to use. But lately I'm just using CDE.ljs from my CDE library so I'm not sure how stable this was (but I think it was stable..).

The script does not pollute the global scope except for the namespace you give it ("Ajax" by default) and has no other dependencies.

Hope it helps ya :)

modified the script to add another option to disable anti-cache-headers for posts; "boolNoAntiCachePost"

2013: Small version of this script, nowadays:

Code:
function get(url, callback){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 || xhr.readyState=='complete') {
if (xhr.status == 200) {
callback(xhr.responseText);
}
}
};
xhr.open('GET', url, true);
xhr.send(null);
}