I am firing an ajax call that handles the insertion of users into the database.
I want to return a string or status code to the ajax success for further use.
If I use res.send() server side it overwrites the current document and display the response in the top left in a black document.
I tried using return but that didn’t work either, unless I’m doing something wrong.
Client Side
$.ajax({
url: "/register",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ data: data }),
success: function (response) {
console.log(response);
Swal.fire({
title: "Success!",
text: "All good",
icon: "success",
});
},
error: function (e) {
Swal.fire({
title: "Error!",
text: "There was an error saving to the database",
icon: "error",
});
console.log(e);
},
});
Server Side
router.post("/", async (req, res) => {
req.body = sanitize(req.body);
const user = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try {
await user.save();
return true;
} catch (e) {
return false;
// Implement response to the user if for some reason the save failed
}
});