I'm writing a pixel library to do an AJAX request so I'm not allowed to use any helper.
function ajax(options) {
var xhr = new XMLHttpRequest();
var opts = Object.assign({
withCredentials: false,
method: 'GET'
}, options);
xhr.withCredentials = options.withCredentials;
xhr.open(opts.method, opts.url);
xhr.setRequestHeader('Accept', 'text/plain');
xhr.send(null);
return {
done: function(cb) {
xhr.onreadystatechange = function onStateChange() {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 300) {
cb(this.responseText);
} else {
cb('error');
}
}
};
xhr.ontimeout = function(e) {
console.error(e);
cb(false);
};
xhr.onerror = function(e) {
console.error(e);
cb(false);
};
}
}
};
ajax({
url: '/echo/json'
}).done(function(response) {
console.log(response);
})
I also have my code in a jsfiddle in case anyone wants to test the code.
Note: This library doesn't support POST as I want to keep the code as less as possible. It will only support GET.