Consider a simple form which takes email as input. Submit button calls a bootstrap modal in case authentication failed. If at success, it redirects to the next view.
When bootstrap modal appears, the browser is constantly loading the page, waiting a response.
I am using this code on server side:
app.post('/', (req, res) => {
Users.findOne({
email: req.body.email
})
.then(user => {
if (user) {
obj = req.body.email
res.redirect('/survey')
}
})
})
I tried to add an else
statement in case user is not found:
...
else {
console.log('User not found')
return
}
I do not want to redirect to the same page because modal will not work.
Is there a res
method in order to achieve this?
How do you stay in the same page after submit a form in HTML? In order to stay on the same page on submit you can leave action empty ( action=”” ) into the form tag, or leave it out altogether. For the message, create a variable ( $message = “Success!
The res. redirect() function redirects to the URL derived from the specified path, with specified status, a integer (positive) which corresponds to an HTTP status code.
The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below.
The proper solution will be to use ajax for submitting form data & handling response
based on the response success / failure, you can redirect user or show modal for error from client side
If you still want to do it without ajax submission of form, you can redirect user to same url with adding querystring
res.redirect('/same-path?error=user_not_found')
And check query params on load of page in client javascript
$(document).ready ( function(){
var url = window.location.search;
var queryStr = url.split("?")[1];
if(queryStr) {
let hash = queryStr.split('&);
for (var i = 0; i < hash.length; i++) {
params=hash[i].split("=");
if(params[0] == 'error' && params[1] == 'user_not_found') {
// SHOW YOUR MODAL HERE
}
}
}
});
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