Fix login/register system
[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 let res_json = "";
30 try {
31 res_json = JSON.parse(xhr.responseText);
32 } catch (e) {
33 // Plain text (e.g. for rules retrieval)
34 return success(xhr.responseText);
35 }
36 if (!res_json.errmsg)
37 success(res_json);
38 else
39 error(res_json.errmsg);
40 }
41 };
42
43 if (["GET","DELETE"].includes(method) && !!data)
44 {
45 // Append query params to URL
46 url += "/?" + toQueryString(data);
47 }
48 xhr.open(method, params.serverUrl + url, true);
49 xhr.setRequestHeader('X-Requested-With', "XMLHttpRequest");
50 // Next line because logout and authenticate set (cross-domain in dev mode) cookies
51 if (url.startsWith("/authenticate") || url.startsWith("/logout"))
52 xhr.withCredentials = true;
53 if (["POST","PUT"].includes(method))
54 {
55 xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
56 xhr.send(JSON.stringify(data));
57 }
58 else
59 xhr.send();
60 }