grid-apps-cmms/src/moto/ajax.js

82 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-06-03 22:39:30 -04:00
/** Copyright Stewart Allen <sa@grid.space> -- All Rights Reserved */
2017-04-18 22:22:29 -04:00
2017-04-18 17:09:33 -04:00
"use strict";
(function() {
2021-12-26 22:49:41 -05:00
let moto = self.moto = self.moto || {};
if (moto.Ajax) return;
2020-04-07 21:45:21 -04:00
2021-12-26 22:49:41 -05:00
moto.Ajax = Ajax;
2020-04-07 21:45:21 -04:00
2021-12-26 22:49:41 -05:00
moto.callAjax = function(url, handler) {
2017-04-18 17:09:33 -04:00
new Ajax(handler).request(url);
};
2020-06-03 22:39:30 -04:00
const AP = Ajax.prototype,
2021-12-28 16:38:05 -05:00
KV = data.Local,
2020-04-07 21:45:21 -04:00
KEY = "moto-ajax",
TIME = function() { return new Date().getTime() },
MOKEY = moto.id = KV.getItem(KEY) || (TIME().toString(36)+rnd()+rnd());
2021-12-26 22:49:41 -05:00
moto.restore = function(id) {
2020-04-07 21:45:21 -04:00
MOKEY = moto.id = id;
KV.setItem(KEY, MOKEY);
}
KV.setItem(KEY, MOKEY);
2020-06-03 22:39:30 -04:00
const STATES = [
2017-04-18 17:09:33 -04:00
"request not initialized", // 0
"server connection established", // 1
"request recieved", // 2
"processing request", // 3
"request complete" // 4
];
function Ajax(callback, responseType) {
this.ajax = new XMLHttpRequest();
this.ajax.onreadystatechange = this.onStateChange.bind(this);
this.ajax.withCredentials = true;
this.state = STATES[0];
this.callback = callback;
this.responseType = responseType;
}
function rnd() {
return Math.round(Math.random()*0xffffffff).toString(36);
}
AP.onStateChange = function() {
this.state = STATES[this.ajax.readyState];
if (this.ajax.readyState === 4 && this.callback) {
2020-04-07 21:45:21 -04:00
let status = this.ajax.status;
2017-04-18 17:09:33 -04:00
if (status >= 200 && status < 300) {
this.callback(this.ajax.responseType ? this.ajax.response : this.ajax.responseText, this.ajax);
} else {
this.callback(null, this.ajax);
}
}
};
/**
* @param {String} url
* @param {Object} [send]
* @param {Object} [headers]
*/
AP.request = function(url, send, headers) {
this.ajax.open(send ? "POST" : "GET", url, true);
if (this.responseType) this.ajax.responseType = this.responseType;
headers = headers || {};
headers["X-Moto-Ajax"] = MOKEY;
2020-04-07 21:45:21 -04:00
for (let k in headers) {
2017-04-18 17:09:33 -04:00
this.ajax.setRequestHeader(k, headers[k]);
}
if (send) {
this.ajax.send(send);
} else {
this.ajax.send();
}
};
})();