1 import params
from "../parameters"; //for server URL
3 // From JSON (encoded string values!) to "arg1=...&arg2=..."
4 function toQueryString(data
)
7 Object
.keys(data
).forEach(k
=> {
8 data_str
+= k
+ "=" + encodeURIComponent(data
[k
]) + "&";
10 return data_str
.slice(0, -1); //remove last "&"
13 // data, error: optional
14 export function ajax(url
, method
, data
, success
, error
)
16 let xhr
= new XMLHttpRequest();
17 if (typeof(data
) === "function") //no data
24 error
= errmsg
=> { alert(errmsg
); };
26 xhr
.onreadystatechange = function() {
27 if (this.readyState
== 4 && this.status
== 200)
31 res_json
= JSON
.parse(xhr
.responseText
);
33 // Plain text (e.g. for rules retrieval)
34 return success(xhr
.responseText
);
39 error(res_json
.errmsg
);
43 if (["GET","DELETE"].includes(method
) && !!data
)
45 // Append query params to URL
46 url
+= "/?" + toQueryString(data
);
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
))
55 xhr
.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
56 xhr
.send(JSON
.stringify(data
));