Skip to content

Instantly share code, notes, and snippets.

@Scribblerockerz
Last active December 24, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Scribblerockerz/6875954 to your computer and use it in GitHub Desktop.
Save Scribblerockerz/6875954 to your computer and use it in GitHub Desktop.
Minimal ajax function. No fallback for older browsers (lt IE7).
;(function(exports){
exports.ajax = function(opt){
var req = new XMLHttpRequest(),
res,
opt = opt || {};
//defaults
opt.success = opt.success || function(){};
opt.params = opt.params || {};
opt.type = opt.type || 'GET';
opt.contentType = opt.contentType || "application/x-www-form-urlencoded";
//default events
req.onerror = opt.failure;
req.onabort = opt.abort;
req.onload = opt.load;
opt._params = "";
for(p in opt.params){
opt._params += p +"="+ encodeURI(opt.params[p]) +"&";
}
req.onreadystatechange = function(){
if(req.readyState < 4) return;
if(req.status < 200 && req.status > 206) return;
try {
res = JSON.parse(req.responseText);
}catch(e){
res = req.responseText;
}
opt.success(res, req);
}
if(opt.type == 'GET'){
req.open(opt.type, opt.url+"?"+opt._params, true);
req.send(null);
}else{
// default alternative is POST
req.open(opt.type, opt.url, true);
req.setRequestHeader("Content-type", opt.contentType);
req.send(opt._params);
}
}
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment