-1

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();
    res.status(200).send("Success");
  } catch (e) {
    res.status(500).send("Error");
    // Implement response to the user if for some reason the save failed
  }
});
dfddsf
  • 1
  • 1
  • Is this ajax being done inside a form submit perhaps? The symptoms don't make sense for an ajax request. Also the route shown has no `send()` – charlietfl Dec 12 '21 at 23:05
  • Sorry that was the latest method I tried. I updated the question to what I tried originally. And yes the submit button calls a js function that does some input validation and the submits the document. – dfddsf Dec 12 '21 at 23:09
  • 1
    So the problem is more likely that you aren't preventing the default form submit and page is reloading. Show us the submit code and can you confirm page reloads? – charlietfl Dec 12 '21 at 23:09

1 Answers1

0

I had the ajax call wraped in a function that I didn't call anywhere and I was just doing a regular form submit as the default. CLOSED

dfddsf
  • 1
  • 1