Skip to content

Instantly share code, notes, and snippets.

@z-------------
Last active September 1, 2015 01:30
Show Gist options
  • Select an option

  • Save z-------------/c7b0add5b0b299e26950 to your computer and use it in GitHub Desktop.

Select an option

Save z-------------/c7b0add5b0b299e26950 to your computer and use it in GitHub Desktop.
/**
* Send HTTP requests using XMLHttpRequest
* @param {string} url The url to which to send the request
* @param {object} options Configuration like verb and parameters
* @param {function} callback The function to run after a response is received
* @returns undefined
* @example
* xhr("http://example.com/api/endpoint", { params: { hello: "world", tau: "2pi" } }, function(res, headers) { doStuff(); } );
*/
var xhr = function(url, options, callback) {
var params, verb;
// check that both args are present and of correct type
if (!(url && typeof url === "string" && url.length > 0)) {
throw new Error("missing url");
}
// set unset options to defaults
if (!options) {
options = {};
}
if (!options.verb) {
options.verb = "get";
}
if (!options.bodyEncoding) {
options.bodyEncoding = "application/json";
}
if (!callback) {
callback = function(res, headers) {
console.log(res);
}
}
verb = options.verb.toLowerCase();
// create the XMLHttpRequest and attach load handler
var req = new XMLHttpRequest();
req.onload = function() {
var response = this.response;
callback(response);
};
// make parameters string
if (options.params && options.params instanceof Object && Object.keys(options.params).length > 0) {
var paramsArray = [];
for (key in options.params) {
if (options.params.hasOwnProperty(key)) {
var val = options.params[key];
paramsArray.push(key + "=" + val);
}
}
params = paramsArray.join("&");
}
req.open(options.verb, url, true);
if (options.verb.toLowerCase() === "get") {
url += ("?" + params);
req.send();
} else if (options.verb.toLowerCase() === "post") {
req.setRequestHeader("Connection", "close");
if (options.bodyEncoding.toLowerCase === "form") {
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
req.setRequestHeader("Content-Length", params.length);
req.send(params);
} else if (options.bodyEncoding.toLowerCase() === "json") {
req.setRequestHeader("Content-Type", "application/json");
req.send(options.params);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment