summaryrefslogtreecommitdiff
path: root/assets/js/core/http.js
diff options
context:
space:
mode:
Diffstat (limited to 'assets/js/core/http.js')
-rw-r--r--assets/js/core/http.js66
1 files changed, 66 insertions, 0 deletions
diff --git a/assets/js/core/http.js b/assets/js/core/http.js
new file mode 100644
index 00000000..b965ad23
--- /dev/null
+++ b/assets/js/core/http.js
@@ -0,0 +1,66 @@
+KB.http.request = function (method, url, headers, body) {
+ var successCallback = function() {};
+ var errorCallback = function() {};
+
+ function parseResponse(request) {
+ try {
+ return JSON.parse(request.responseText);
+ } catch (e) {
+ return request.responseText;
+ }
+ }
+
+ this.execute = function () {
+ var request = new XMLHttpRequest();
+ request.open(method, url, true);
+ request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
+
+ for (var header in headers) {
+ if (headers.hasOwnProperty(header)) {
+ request.setRequestHeader(header, headers[header]);
+ }
+ }
+
+ request.onerror = function() {
+ errorCallback();
+ };
+
+ request.onreadystatechange = function() {
+ if (request.readyState === XMLHttpRequest.DONE) {
+ var response = parseResponse(request);
+
+ if (request.status === 200) {
+ successCallback(response);
+ } else {
+ errorCallback(response);
+ }
+ }
+ };
+
+ request.send(body);
+ return this;
+ };
+
+ this.success = function (callback) {
+ successCallback = callback;
+ return this;
+ };
+
+ this.error = function (callback) {
+ errorCallback = callback;
+ return this;
+ };
+};
+
+KB.http.get = function (url) {
+ return (new KB.http.request('GET', url)).execute();
+};
+
+KB.http.postJson = function (url, body) {
+ var headers = {
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json'
+ };
+
+ return (new KB.http.request('POST', url, headers, JSON.stringify(body))).execute();
+};