Skip to content

Instantly share code, notes, and snippets.

@Scribblerockerz
Last active Dec 24, 2015
Embed
What would you like to do?
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