GameStorage: experimental refactor
[vchess.git] / client / src / utils / ajax.js
CommitLineData
03470390
BA
1import params from "../parameters"; //for server URL
2
da06a6eb
BA
3// From JSON (encoded string values!) to "arg1=...&arg2=..."
4function toQueryString(data)
5{
6 let data_str = "";
7 Object.keys(data).forEach(k => {
b57dbd12 8 data_str += k + "=" + encodeURIComponent(data[k]) + "&";
da06a6eb
BA
9 });
10 return data_str.slice(0, -1); //remove last "&"
11}
12
13// data, error: optional
625022fd 14export function ajax(url, method, data, success, error)
da06a6eb
BA
15{
16 let xhr = new XMLHttpRequest();
17 if (typeof(data) === "function") //no data
18 {
19 error = success;
20 success = data;
21 data = {};
22 }
23 if (!error)
24 error = errmsg => { alert(errmsg); };
25
26 xhr.onreadystatechange = function() {
27 if (this.readyState == 4 && this.status == 200)
28 {
1aeed627 29 let res_json = "";
da06a6eb 30 try {
1aeed627
BA
31 res_json = JSON.parse(xhr.responseText);
32 } catch (e) {
da06a6eb 33 // Plain text (e.g. for rules retrieval)
1aeed627
BA
34 return success(xhr.responseText);
35 }
36 if (!res_json.errmsg)
37 success(res_json);
38 else
39 error(res_json.errmsg);
da06a6eb
BA
40 }
41 };
42
43 if (["GET","DELETE"].includes(method) && !!data)
44 {
45 // Append query params to URL
46 url += "/?" + toQueryString(data);
47 }
03470390 48 xhr.open(method, params.serverUrl + url, true);
da06a6eb 49 xhr.setRequestHeader('X-Requested-With', "XMLHttpRequest");
deca03e8 50 // Next line to allow cross-domain cookies in dev mode (TODO: if...)
98f48579
BA
51 if (params.cors)
52 xhr.withCredentials = true;
1aeed627 53 if (["POST","PUT"].includes(method))
da06a6eb
BA
54 {
55 xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
56 xhr.send(JSON.stringify(data));
57 }
58 else
59 xhr.send();
60}