X-Git-Url: https://git.auder.net/img/rock_paper_scissors_lizard_spock.gif?a=blobdiff_plain;f=client%2Fsrc%2Futils%2Fajax.js;h=01ea84935f132ebf7713cbf4f7a242eea3ffe791;hb=e64c6f67185b45b3b1205069532362c1bf9680db;hp=46edca06b953068ebeb4391730207db51d9014e9;hpb=03470390eba8fd75b6aa5d929140d16a4aa719b9;p=vchess.git diff --git a/client/src/utils/ajax.js b/client/src/utils/ajax.js index 46edca06..01ea8493 100644 --- a/client/src/utils/ajax.js +++ b/client/src/utils/ajax.js @@ -1,5 +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) { @@ -26,16 +29,17 @@ export function ajax(url, method, data, success, error) 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) + success(res_json); + else + error(res_json.errmsg); } }; @@ -46,7 +50,10 @@ export function ajax(url, method, data, success, error) } 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));