From b4de2e730539cadbff94a42eccfb9cb046cbf810 Mon Sep 17 00:00:00 2001
From: Benjamin Auder <benjamin.auder@somewhere>
Date: Fri, 29 Nov 2019 15:20:29 +0100
Subject: [PATCH] Fix ajax for challenge creation

---
 client/src/utils/ajax.js    | 5 +++--
 server/models/Challenge.js  | 2 +-
 server/routes/challenges.js | 5 ++---
 3 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/client/src/utils/ajax.js b/client/src/utils/ajax.js
index 01ea8493..5b460784 100644
--- a/client/src/utils/ajax.js
+++ b/client/src/utils/ajax.js
@@ -17,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)
 		{
diff --git a/server/models/Challenge.js b/server/models/Challenge.js
index 82b252fd..c988aba5 100644
--- a/server/models/Challenge.js
+++ b/server/models/Challenge.js
@@ -35,7 +35,7 @@ const ChallengeModel =
         "(" + Date.now() + "," + c.uid + "," + (!!c.to ? c.to + "," : "") +
           c.vid + ",'" + c.fen + "','" + c.timeControl + "')";
       db.run(query, err => {
-        return cb(err);
+        return cb(err, {cid: this.lastID});
       });
     });
   },
diff --git a/server/routes/challenges.js b/server/routes/challenges.js
index c2e55c8a..acec3c13 100644
--- a/server/routes/challenges.js
+++ b/server/routes/challenges.js
@@ -24,9 +24,8 @@ router.post("/challenges", access.logged, access.ajax, (req,res) => {
     to: req.body.chall.to, //string: user name (may be empty)
   };
   const insertChallenge = () => {
-    ChallengeModel.create(challenge, (err) => {
-      if (!!err)
-        return res.json(err);
+    ChallengeModel.create(challenge, (err,ret) => {
+      return res.json(err || {cid:ret.cid});
     });
   };
   if (!!req.body.chall.to)
-- 
2.44.0