After submitting a form I want to render the same page but with a 'message sent successfully' message above the form. With this code I get 'reference error, msg not defined', which I find strange as when I use the same code but in the GET request it works perfectly. Is there a different technique between GET and POST requests?
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
app.get('/contact', (req, res) => {
res.render('contact');
});
app.post('/send', (req, res) => {
res.render('contact', {msg: 'Message sent successfully!'});
});
<section class="section-b">
<div>
<p><%= msg %></p>
<form action="send" id="contact-form" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="email" name="emailContact" placeholder="E-mail"><br>
<textarea name="message" id="message" rows="10" placeholder="Your message here..."></textarea><br>
<button type="submit">Submit</button>
</form>
</div>
</section>
You need to check if the variable (msg) is defined, in the .get("/contact") request you are not sending the msg as a parameter, so that's why you are getting the error
<% if(typeof msg !== 'undefined') { %>
<p><%= msg %></p>
<% } %>
Conclusion based on @Chiller answer, if you don't want to use <% if(typeof msg !== 'undefined') { %> you need to define msg variable in the .get method, for example:
app.get('/contact', (req, res) => {
res.render('contact', {msg: '')};
});
app.post('/send', (req, res) => {
res.render('contact', {msg: 'Message sent successfully!'});
});
then, you can use <p><%= msg %></p> in your .ejs file without checking if variable is undefined.
But I prefer @Chiller answer as well.
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