Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait before res.redirect()

I have a button in my HTML file which calls a post route when it's clicked and submits a form. The button click also calls a function in my other javascript file that activates a 'sweetalert' alert box.

However, the problem that I have now is that the user does not get enough time to read the alert before the post request executes res.redirect("/").

I was hoping for any one of the following solutions:

1) Call the alert after the page is redirected (I read somewhere that you cannot control the next page with node.js so this may not be possible).

2) Wait a few seconds before res.redirect("/") is called.

3) Any other appropriate solution.

HTML file that contains the button:

<button formaction="/removetask" type="submit" id="top" class="btn btn-primary btn-block" onclick="success()"> Complete </button>

client-side javascript file:

function success(){
  ...
  swal("Congratulations!", "Goal successfully completed", "success")

}

node.js file:

app.post("/removetask", async function(req, res) {
  ...
  res.redirect("/");  
});

link to 'sweetalert' in HTML:

<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

EDIT:

I notice that using the regular HTML alert() stops everything and prevents redirection until the user has closed the alert. Is it possible to change the 'sweetalert` alert to behave like this?

like image 797
bgmn Avatar asked Sep 06 '25 21:09

bgmn


2 Answers

I changed your code a little bit. Now by clicking form is not submiting.

Jest after you click on the success button the form will be submitted.

HTML:

<button type="button" id="top" class="btn btn-primary btn-block" onclick="success()"> Complete </button>

JS:

function success(){
  swal({
  title: "Congratulations!",
  text: "Goal successfully completed",
  type: "success",
  }).then(function(){ 
      document.getElementById('form').submit();
  });
}

https://code.sololearn.com/WGoSH0qXkP9I/#html

like image 146
אברימי פרידמן Avatar answered Sep 09 '25 14:09

אברימי פרידמן


You can try other ways to display alarms.

First, you don't need to redirect to original page.

app.post("/removetask", async function(req, res) {
  ...
  res.render('alarm page') 
});

And on the alarm page, the javascript file will set the time to wait for a moment.

alarmpagejs.js follow

  setTimeout(() => {
     window.location = "/";
  }, 5000)

Then the result will be this logic:

  1. button click
  2. rendering alarm page
  3. redirecting to '/' by alarm page.js

You can wait for an arbitrary amount of milliseconds

like image 45
Minwoo Yu Avatar answered Sep 09 '25 14:09

Minwoo Yu