Separate timeControl logic into utils/timeControl
[vchess.git] / client / src / utils / ajax.js
1 import params from "../parameters"; //for server URL
2
3 // From JSON (encoded string values!) to "arg1=...&arg2=..."
4 function toQueryString(data)
5 {
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 "&"
11 }
12
13 // data, error: optional
14 export function ajax(url, method, data, success, error)
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 {
29 try {
30 let res_json = JSON.parse(xhr.responseText);
31 if (!res_json.errmsg)
32 success(res_json);
33 else
34 error(res_json.errmsg);
35 } catch (e) {
36 // Plain text (e.g. for rules retrieval)
37 success(xhr.responseText);
38 }
39 }
40 };
41
42 if (["GET","DELETE"].includes(method) && !!data)
43 {
44 // Append query params to URL
45 url += "/?" + toQueryString(data);
46 }
47 xhr.open(method, params.serverUrl + url, true);
48 xhr.setRequestHeader('X-Requested-With', "XMLHttpRequest");
49 if (["POST","PUT"].includes(method))
50 {
51 xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
52 xhr.send(JSON.stringify(data));
53 }
54 else
55 xhr.send();
56 }