Commit | Line | Data |
---|---|---|
03470390 | 1 | import params from "../parameters"; //for server URL |
f0c68a04 | 2 | import { store } from "../store"; //for translations |
03470390 | 3 | |
da06a6eb | 4 | // From JSON (encoded string values!) to "arg1=...&arg2=..." |
6808d7a1 | 5 | function toQueryString(data) { |
dac39588 BA |
6 | let data_str = ""; |
7 | Object.keys(data).forEach(k => { | |
8 | data_str += k + "=" + encodeURIComponent(data[k]) + "&"; | |
9 | }); | |
10 | return data_str.slice(0, -1); //remove last "&" | |
da06a6eb BA |
11 | } |
12 | ||
e57c4de4 BA |
13 | // TODO: use this syntax https://stackoverflow.com/a/29823632 ? |
14 | // data, success, error: optional | |
15 | export function ajax(url, method, options) { | |
d9a7a1e4 | 16 | options = options || {}; |
e57c4de4 BA |
17 | const data = options.data || {}; |
18 | // By default, do nothing on success and print errors: | |
19 | if (!options.success) | |
20 | options.success = () => {}; | |
21 | if (!options.error) { | |
22 | options.error = (errmsg) => { | |
f0c68a04 | 23 | alert(store.state.tr[errmsg] || errmsg); |
6808d7a1 | 24 | }; |
e57c4de4 BA |
25 | } |
26 | if (["GET", "DELETE"].includes(method) && !!data) | |
dac39588 BA |
27 | // Append query params to URL |
28 | url += "/?" + toQueryString(data); | |
e57c4de4 BA |
29 | const headers = { |
30 | "Content-Type": "application/json;charset=UTF-8", | |
31 | "X-Requested-With": "XMLHttpRequest" | |
32 | }; | |
33 | let fetchOptions = { | |
34 | method: method, | |
35 | headers: headers, | |
36 | }; | |
37 | if (["POST", "PUT"].includes(method)) | |
38 | fetchOptions["body"] = JSON.stringify(data); | |
39 | if ( | |
40 | !!options.credentials || | |
41 | (method != "GET" && !options.nocredentials) | |
42 | ) { | |
43 | fetchOptions["credentials"] = params.credentials; | |
dac39588 | 44 | } |
e57c4de4 BA |
45 | fetch(params.serverUrl + url, fetchOptions) |
46 | .then(res => res.json()) | |
47 | .then(json => { | |
48 | if (!json.errmsg && !json.errno) options.success(json); | |
49 | else { | |
50 | if (!!json.errmsg) options.error(json.errmsg); | |
51 | else options.error(json.code + ". errno = " + json.errno); | |
52 | } | |
53 | }); | |
da06a6eb | 54 | } |