Replaced AJAX by fetch: not everything tested yet, but seems fine
[vchess.git] / client / src / utils / ajax.js
CommitLineData
03470390 1import params from "../parameters"; //for server URL
f0c68a04 2import { store } from "../store"; //for translations
03470390 3
da06a6eb 4// From JSON (encoded string values!) to "arg1=...&arg2=..."
6808d7a1 5function 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
15export function ajax(url, method, options) {
16 const data = options.data || {};
17 // By default, do nothing on success and print errors:
18 if (!options.success)
19 options.success = () => {};
20 if (!options.error) {
21 options.error = (errmsg) => {
f0c68a04 22 alert(store.state.tr[errmsg] || errmsg);
6808d7a1 23 };
e57c4de4
BA
24 }
25 if (["GET", "DELETE"].includes(method) && !!data)
dac39588
BA
26 // Append query params to URL
27 url += "/?" + toQueryString(data);
e57c4de4
BA
28 const headers = {
29 "Content-Type": "application/json;charset=UTF-8",
30 "X-Requested-With": "XMLHttpRequest"
31 };
32 let fetchOptions = {
33 method: method,
34 headers: headers,
35 };
36 if (["POST", "PUT"].includes(method))
37 fetchOptions["body"] = JSON.stringify(data);
38 if (
39 !!options.credentials ||
40 (method != "GET" && !options.nocredentials)
41 ) {
42 fetchOptions["credentials"] = params.credentials;
dac39588 43 }
e57c4de4
BA
44 fetch(params.serverUrl + url, fetchOptions)
45 .then(res => res.json())
46 .then(json => {
47 if (!json.errmsg && !json.errno) options.success(json);
48 else {
49 if (!!json.errmsg) options.error(json.errmsg);
50 else options.error(json.code + ". errno = " + json.errno);
51 }
52 });
da06a6eb 53}