1 import params
from "../parameters"; //for server URL
2 import { store
} from "../store"; //for translations
4 // TODO: replace by fetch API ?
5 // https://www.sitepoint.com/xmlhttprequest-vs-the-fetch-api-whats-best-for-ajax-in-2019/
7 // From JSON (encoded string values!) to "arg1=...&arg2=..."
8 function toQueryString(data
) {
10 Object
.keys(data
).forEach(k
=> {
11 data_str
+= k
+ "=" + encodeURIComponent(data
[k
]) + "&";
13 return data_str
.slice(0, -1); //remove last "&"
16 // data, error: optional
17 export function ajax(url
, method
, data
, success
, error
) {
18 let xhr
= new XMLHttpRequest();
19 if (data
=== undefined || typeof data
=== "function") {
25 if (!success
) success
= () => {}; //by default, do nothing
28 alert(store
.state
.tr
[errmsg
] || errmsg
);
30 xhr
.onreadystatechange = function() {
31 if (this.readyState
== 4 && this.status
== 200) {
34 res_json
= JSON
.parse(xhr
.responseText
);
36 // Plain text (e.g. for rules retrieval) (TODO: no more plain text in current version)
37 success(xhr
.responseText
);
40 if (!res_json
.errmsg
&& !res_json
.errno
) success(res_json
);
42 if (res_json
.errmsg
) error(res_json
.errmsg
);
43 else error(res_json
.code
+ ". errno = " + res_json
.errno
);
49 if (["GET", "DELETE"].includes(method
) && !!data
) {
50 // Append query params to URL
51 url
+= "/?" + toQueryString(data
);
53 xhr
.open(method
, params
.serverUrl
+ url
, true);
54 xhr
.setRequestHeader("X-Requested-With", "XMLHttpRequest");
55 // Next line to allow cross-domain cookies in dev mode
56 if (params
.cors
) xhr
.withCredentials
= true;
57 if (["POST", "PUT"].includes(method
)) {
58 xhr
.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
59 xhr
.send(JSON
.stringify(data
));