Skip to content

Instantly share code, notes, and snippets.

@janbiasi
Last active February 3, 2016 19:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save janbiasi/657a03c7f9c8f26bbf00 to your computer and use it in GitHub Desktop.
Save janbiasi/657a03c7f9c8f26bbf00 to your computer and use it in GitHub Desktop.
ajax
(function(window, undefined) {
var strEq = function(str1, str2) {
return str1.toLowerCase() === str2.toLowerCase();
};
var ajaxRequest = function(method, opts) {
opts = opts ? opts : {};
opts.data = opts.data || null;
opts.success = opts.success || function() { };
opts.error = opts.error || function(data, code) {
throw new Error("Ajax abortet with statuscode " + code);
};
opts.async = opts.async || false;
opts.url = opts.url || null;
if(opts.url == null) {
return console.error("Can\'t create a request because the target url is empty");
}
var xhr = new XMLHttpRequest();
xhr.open(method, opts.url, opts.async);
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200) {
return opts.error(xhr.responseText, xhr.status);
}
opts.success(xhr.responseText);
};
r.send(opts.data);
};
var ajaxGet = function(opts) {
return ajaxRequest("GET", opts);
};
var ajaxPost = function(opts) {
return ajaxRequest("POST", opts)
};
var ajax = function(opts) {
if(strEq(opts.type, "get")) {
return ajaxGet;
} else {
return ajaxPost;
}
};
window.ajax = ajax;
})(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment