Fix ajax for challenge creation
[vchess.git] / client / src / utils / ajax.js
index 1d181fa..5b46078 100644 (file)
@@ -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)
 {
@@ -14,15 +17,16 @@ 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)
                {
@@ -48,7 +52,8 @@ export function ajax(url, method, data, success, error)
        xhr.open(method, params.serverUrl + url, true);
        xhr.setRequestHeader('X-Requested-With', "XMLHttpRequest");
        // Next line to allow cross-domain cookies in dev mode (TODO: if...)
-  xhr.withCredentials = true;
+  if (params.cors)
+    xhr.withCredentials = true;
   if (["POST","PUT"].includes(method))
        {
                xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");