Skip to content

Instantly share code, notes, and snippets.

@hitecherik
Last active September 7, 2016 13:35
Show Gist options
  • Save hitecherik/80afa27223c7cbc636e617a106865745 to your computer and use it in GitHub Desktop.
Save hitecherik/80afa27223c7cbc636e617a106865745 to your computer and use it in GitHub Desktop.
A small group of functions for handling POST and GET requests so I don't always have to write out the same stuff
(function() {
function newXHR() {
if (window.ActiveXObject) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
console.error(e.message);
return null;
}
}
return new XMLHttpRequest();
}
function get(url, callback) {
var xhr = newXHR();
xhr.open("GET", url);
xhr.onload = function() {
callback.call(xhr);
};
xhr.send();
}
function post(url, args, callback) {
var argString = args,
xhr = newXHR();
if (args instanceof Object) {
var keys = Object.keys(args);
argString = "";
for (var i = 0; i < keys.length; i++) {
if (argString.length > 0) {
argString += "&";
}
argString += encodeURI(keys[i] + "=" + args[keys[i]]);
}
}
xhr.open("POST", url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
callback.call(xhr);
}
xhr.send(argString);
}
window.ajax = {
get: get,
post: post
}
})();
// GET request
ajax.get("http://example.com", function() {
console.log("Status code: " + this.status);
console.log("Response text: " + this.responseText);
});
// POST requests
ajax.post("http://example.com", "hello=world&foo=bar", function() {
console.log("Status code: " + this.status);
console.log("Response text: " + this.responseText);
});
var args = {
hello: "world",
foo: "bar"
}
ajax.post("http://example.com", args, function() {
console.log("Status code: " + this.status);
console.log("Response text: " + this.responseText);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment