1 import params
from "../parameters"; //for server URL
2 import { store
} from "../store"; //for translations
4 // From JSON (encoded string values!) to "arg1=...&arg2=..."
5 function toQueryString(data
) {
7 Object
.keys(data
).forEach(k
=> {
8 data_str
+= k
+ "=" + encodeURIComponent(data
[k
]) + "&";
10 return data_str
.slice(0, -1); //remove last "&"
13 // TODO: use this syntax https://stackoverflow.com/a/29823632 ?
14 // data, success, error: optional
15 export function ajax(url
, method
, options
) {
16 const data
= options
.data
|| {};
17 // By default, do nothing on success and print errors:
19 options
.success
= () => {};
21 options
.error
= (errmsg
) => {
22 alert(store
.state
.tr
[errmsg
] || errmsg
);
25 if (["GET", "DELETE"].includes(method
) && !!data
)
26 // Append query params to URL
27 url
+= "/?" + toQueryString(data
);
29 "Content-Type": "application/json;charset=UTF-8",
30 "X-Requested-With": "XMLHttpRequest"
36 if (["POST", "PUT"].includes(method
))
37 fetchOptions
["body"] = JSON
.stringify(data
);
39 !!options
.credentials
||
40 (method
!= "GET" && !options
.nocredentials
)
42 fetchOptions
["credentials"] = params
.credentials
;
44 fetch(params
.serverUrl
+ url
, fetchOptions
)
45 .then(res
=> res
.json())
47 if (!json
.errmsg
&& !json
.errno
) options
.success(json
);
49 if (!!json
.errmsg
) options
.error(json
.errmsg
);
50 else options
.error(json
.code
+ ". errno = " + json
.errno
);