Skip to content

Instantly share code, notes, and snippets.

@brunomrpx
Last active December 3, 2015 00:44
Show Gist options
  • Save brunomrpx/e4b030cc2b35319786a4 to your computer and use it in GitHub Desktop.
Save brunomrpx/e4b030cc2b35319786a4 to your computer and use it in GitHub Desktop.
Simple object to make Ajax requests
var ajax = (function() {
'use strict';
var xmlHttpRequest;
var states = {
UNSET: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4
};
var defaultHeaders = [
{
'Content-Type': 'application/x-www-form-urlencoded'
}
];
function send(url, options) {
xmlHttpRequest = new XMLHttpRequest();
options.method = options.method || '';
options.data = options.data || '';
xmlHttpRequest.addEventListener('readystatechange', function() {
if (this.readyState == states.DONE) {
if (options.callback && typeof options.callback == 'function') {
options.callback(xmlHttpRequest);
}
}
});
xmlHttpRequest.open(options.method, url);
configure(options.configuration || {});
xmlHttpRequest.send(options.data || null);
}
function addHeaders(headersList) {
var headerItem,
index,
headerValue,
headerName;
for (index in headersList) {
headerItem = headersList[index];
for (headerName in headerItem) {
headerValue = headerItem[headerName];
xmlHttpRequest.setRequestHeader(headerName, headerValue);
}
}
}
function configure(configuration) {
var headersList = configuration.headers || defaultHeaders;
addHeaders(headersList);
xmlHttpRequest.timeout = configuration.timeout || 0;
xmlHttpRequest.responseType = configuration.responseType || "";
}
return {
send: send
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment