-export function ajax(url, method, data, success, error)
-{
- let xhr = new XMLHttpRequest();
- if (typeof(data) === "function") //no data
- {
- error = success;
- success = data;
- data = {};
- }
- if (!error)
- error = errmsg => { alert(errmsg); };
-
- xhr.onreadystatechange = function() {
- if (this.readyState == 4 && this.status == 200)
- {
- try {
- let res_json = JSON.parse(xhr.responseText);
- if (!res_json.errmsg)
- success(res_json);
- else
- error(res_json.errmsg);
- } catch (e) {
- // Plain text (e.g. for rules retrieval)
- success(xhr.responseText);
- }
- }
- };
+export function ajax(url, method, data, success, error) {
+ let xhr = new XMLHttpRequest();
+ if (data === undefined || typeof data === "function") {
+ //no data
+ error = success;
+ success = data;
+ data = {};
+ }
+ if (!success) success = () => {}; //by default, do nothing
+ if (!error)
+ error = errmsg => {
+ alert(errmsg);
+ };
+ xhr.onreadystatechange = function() {
+ if (this.readyState == 4 && this.status == 200) {
+ let res_json = "";
+ try {
+ res_json = JSON.parse(xhr.responseText);
+ } catch (e) {
+ // Plain text (e.g. for rules retrieval) (TODO: no more plain text in current version)
+ success(xhr.responseText);
+ }
+ if (res_json) {
+ if (!res_json.errmsg && !res_json.errno) success(res_json);
+ else {
+ if (res_json.errmsg) error(res_json.errmsg);
+ else error(res_json.code + ". errno = " + res_json.errno);
+ }
+ }
+ }
+ };