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?
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
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:
You can wait for an arbitrary amount of milliseconds
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With