Skip to content

Instantly share code, notes, and snippets.

@tswaters
Last active August 29, 2015 14:23
Show Gist options
  • Save tswaters/a771eee2f8cfff09b60b to your computer and use it in GitHub Desktop.
Save tswaters/a771eee2f8cfff09b60b to your computer and use it in GitHub Desktop.
ajax helper
function ajax (opts) {
if (this instanceof ajax) throw new Error("stop instantiating me!");
if (!opts) throw new Error("pass opts, dummy.")
if (!opts.url) throw new Error("pass url, dummy");
if (!opts.method) throw new Error("pass method, dummy");
var callbacks = {
success: [],
failure: [],
always: []
};
var ret = Object.keys(callbacks).reduce(function(obj, key) {
obj[key] = function (cb) { callbacks[key].push(cb); return ret; };
return obj;
}, {});
var req = new XMLHttpRequest();
req.open(opts.method.toUpperCase(), opts.url);
req.onreadystatechange = function () {
if (!(req.readyState === 4)) { return; }
var ok = req.status >= 200 && req.status < 400;
var fns = callbacks[ok ? "success" : "failure"];
fns.forEach(function (cb) { cb(req); });
callbacks.always.forEach(function (cb) {cb(req); });
};
req.send(opts.data);
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment