X-Git-Url: https://git.auder.net/?a=blobdiff_plain;f=client%2Fsrc%2Futils%2Fajax.js;h=83b045c02bbda02ccd87a2bf24f34848ca4dbea5;hb=6f57a9769ad80459d086abf5232d01ec1ce7a470;hp=065f382517ddf44965c9308a389ef6c6d2802496;hpb=625022fdcf750f0aff8fcd699f7e9b89730e1d10;p=vchess.git diff --git a/client/src/utils/ajax.js b/client/src/utils/ajax.js index 065f3825..83b045c0 100644 --- a/client/src/utils/ajax.js +++ b/client/src/utils/ajax.js @@ -1,3 +1,8 @@ +import params from "../parameters"; //for server URL + +// TODO: replace by fetch API ? +// https://www.sitepoint.com/xmlhttprequest-vs-the-fetch-api-whats-best-for-ajax-in-2019/ + // From JSON (encoded string values!) to "arg1=...&arg2=..." function toQueryString(data) { @@ -12,28 +17,35 @@ function toQueryString(data) export function ajax(url, method, data, success, error) { let xhr = new XMLHttpRequest(); - if (typeof(data) === "function") //no data + if (data === undefined || typeof(data) === "function") //no data { error = success; success = data; data = {}; } + if (!success) + success = () => {}; //by default, do nothing if (!error) error = errmsg => { alert(errmsg); }; - xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { + let res_json = ""; try { - let res_json = JSON.parse(xhr.responseText); - if (!res_json.errmsg) - success(res_json); - else - error(res_json.errmsg); - } catch (e) { + res_json = JSON.parse(xhr.responseText); + } catch (e) { // Plain text (e.g. for rules retrieval) - success(xhr.responseText); - } + return success(xhr.responseText); + } + if (!res_json.errmsg && !res_json.errno) + success(res_json); + else + { + if (!!res_json.errmsg) + error(res_json.errmsg); + else + error(res_json.code + ". errno = " + res_json.errno); + } } }; @@ -42,9 +54,12 @@ export function ajax(url, method, data, success, error) // Append query params to URL url += "/?" + toQueryString(data); } - xhr.open(method, url, true); + xhr.open(method, params.serverUrl + url, true); xhr.setRequestHeader('X-Requested-With', "XMLHttpRequest"); - if (["POST","PUT"].includes(method)) + // Next line to allow cross-domain cookies in dev mode (TODO: if...) + if (params.cors) + xhr.withCredentials = true; + if (["POST","PUT"].includes(method)) { xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send(JSON.stringify(data));