Fix error handling in ajax() function
[vchess.git] / client / src / utils / ajax.js
1 import params from "../parameters"; //for server URL
2
3 // TODO: replace by fetch API ?
4 // https://www.sitepoint.com/xmlhttprequest-vs-the-fetch-api-whats-best-for-ajax-in-2019/
5
6 // From JSON (encoded string values!) to "arg1=...&arg2=..."
7 function toQueryString(data)
8 {
9 let data_str = "";
10 Object.keys(data).forEach(k => {
11 data_str += k + "=" + encodeURIComponent(data[k]) + "&";
12 });
13 return data_str.slice(0, -1); //remove last "&"
14 }
15
16 // data, error: optional
17 export function ajax(url, method, data, success, error)
18 {
19 let xhr = new XMLHttpRequest();
20 if (data === undefined || typeof(data) === "function") //no data
21 {
22 error = success;
23 success = data;
24 data = {};
25 }
26 if (!success)
27 success = () => {}; //by default, do nothing
28 if (!error)
29 error = errmsg => { alert(errmsg); };
30 xhr.onreadystatechange = function() {
31 if (this.readyState == 4 && this.status == 200)
32 {
33 let res_json = "";
34 try {
35 res_json = JSON.parse(xhr.responseText);
36 } catch (e) {
37 // Plain text (e.g. for rules retrieval)
38 return success(xhr.responseText);
39 }
40 if (!res_json.errmsg && !res_json.errno)
41 success(res_json);
42 else
43 {
44 if (!!res_json.errmsg)
45 error(res_json.errmsg);
46 else
47 error(res_json.code + ". errno = " + res_json.errno);
48 }
49 }
50 };
51
52 if (["GET","DELETE"].includes(method) && !!data)
53 {
54 // Append query params to URL
55 url += "/?" + toQueryString(data);
56 }
57 xhr.open(method, params.serverUrl + url, true);
58 xhr.setRequestHeader('X-Requested-With', "XMLHttpRequest");
59 // Next line to allow cross-domain cookies in dev mode (TODO: if...)
60 if (params.cors)
61 xhr.withCredentials = true;
62 if (["POST","PUT"].includes(method))
63 {
64 xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
65 xhr.send(JSON.stringify(data));
66 }
67 else
68 xhr.send();
69 }