0

I would like to do the following:

POST form via fetch then

If the response is an error message (res.json): stay on same page and alert(json.errorMsg)

If the response is a redirect to another page (res.redirect): redirect to new page

The problem is

1) If I use event.preventdefault(), my page does not redirect

2) If I don't use event.preventdefault(), my page always redirect (to a json if there is an error)

Here is summary of my code :

// Client side
form.addEventListener("submit", () => {
  fetch(url, fetchData)
    .then((res) => res.json()) // Transform the data into json
    .then(function (data) {
      alert(data); // Let the user know there was an error in Captcha or provided info
    })
});

// Server side
app.post('/', (req, res) => {
  if (err) {
    console.error(err)
    return res.json({ "success": false, "msg": err })
  }
  return res.redirect("/confirmation_page");
});
Macjeje
  • 37
  • 9
  • https://stackoverflow.com/questions/503093/how-do-i-redirect-to-another-webpage – Max Baldwin Sep 26 '19 at 19:35
  • 1
    In your case you have to use `preventDefault` to prevent your form from submitting. Then you should manually navigate to a different page by using the `location.replace` method. – Emiel Zuurbier Sep 26 '19 at 19:36

2 Answers2

2

Generally this is solved in one of 2 ways:

  1. The form submission is 100% handled in frontend javascript, with for example fetch(). A redirect here is kind of pointless, the redirect should be handled 100% in the frontend.
  2. The form submission is plain HTML. Since validation is one the server, the server would validate the request and if there was a validation error redirect back to the original form.

Since it sounds like you are opting for #1, what you should do is:

  1. Use preventDefault()
  2. If the submission was successful, redirect by calling: document.location = '/confirmation_page';
Evert
  • 93,428
  • 18
  • 118
  • 189
1

Thanks to Emiel and Evert, here is what I changed to make it work:

// Client side
form.addEventListener("submit", () => {
  event.preventDefault();
  fetch(url, fetchData)
    .then((res) => res.json()) // Transform the data into json
    .then(function (data) {
      if (data.success) {
        location.replace("your_url") // redirect page if success
      }
      else {
        alert(data.msg); // Let the user know there was an error in Captcha or provided info
      }

    })
});

// Server side
app.post('/', (req, res) => {
  if (err) {
    console.error(err)
    return res.json({ "success": false, "msg": err })
  }
  return res.json({ "success": true, "msg": "ok" })
});
Macjeje
  • 37
  • 9