Skip to content

Instantly share code, notes, and snippets.

@akhawaja
Created October 24, 2016 15:07
Show Gist options
  • Save akhawaja/f836421aeb58eb1fec674bfaabe64f24 to your computer and use it in GitHub Desktop.
Save akhawaja/f836421aeb58eb1fec674bfaabe64f24 to your computer and use it in GitHub Desktop.
Async Cross-Domain Ajax helper without jQuery and uses Promises.
"use strict";
/**
* Cross-Domain Ajax helper.
* @author Amir Khawaja <[email protected]>
* @license MIT
* @constructor
*/
var XRequest = function () {
var self = this;
self.headers = [];
};
/**
* Make the Ajax request.
* @param {string} method - The HTTP method to use.
* @param {string} url - The URL.
* @param {string} [payload] - The data to send in the request.
*/
XRequest.prototype.send = function (method, url, payload) {
var self = this;
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onload = function () {
if (xhr.status === 200) {
if (xhr.responseText !== void 0 && xhr.responseText.length > 0) {
resolve(xhr.responseText);
} else {
resolve(null);
}
} else if (xhr.status === 403) {
reject(JSON.stringify({
success: false, status: xhr.status, response: ['403 Forbidden - ' + url]
}));
} else if (self.xhr.status === 404) {
reject(JSON.stringify({
success: false, status: xhr.status, response: ['404 Not Found - ' + url]
}));
} else {
reject(JSON.stringify({
success: false, status: xhr.status, response: [xhr.response]
}));
}
};
xhr.onerror = function () {
reject(JSON.stringify({
success: false, status: null, response: 'An error occurred while trying to make the request'
}));
};
// Set the HTTP headers.
if (self.headers.length > 0) {
for (var i in self.headers) {
var key = Object.keys(self.headers[i])[0];
self.xhr.setRequestHeader(key, self.headers[i][key]);
}
}
// Open the connection.
xhr.open(method.toLocaleUpperCase(), url);
// Make the request.
switch (method.toLocaleLowerCase()) {
case 'get':
case 'delete':
xhr.send();
break;
case 'post':
case 'put':
xhr.send(payload);
break;
default:
xhr.send();
break;
}
});
};
/**
* Set HTTP header.
* @param {string} key - The name of the header.
* @param {string} value - The value of the header.
*/
XRequest.prototype.setHeader = function (key, value) {
var self = this;
var obj = {};
obj[key] = value;
self.headers.push(obj);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment