a35469005ff2277bd09325ebe3bfa9005495fb86
[vchess.git] / public / javascripts / 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 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
46 xhr.open(method, url, true);
47 xhr.setRequestHeader('X-Requested-With', "XMLHttpRequest");
48 if (["POST","PUT"].includes(method))
49 {
50 xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
51 xhr.send(JSON.stringify(data));
52 }
53 else
54 xhr.send();
55 }