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