Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ejs template variable is not defined on page load and errors

I have a form submitting to an express app:

app.post('/myform', function (req, res) {
    var content = new registration(req.body);
    content.save(function(errObj){
    if(errObj){
        res.render('registration',{error: errObj});
    } else {
        res.render('thankyou');
    }
});

If there are any errors in saving the form data to mongoDb I want to display those errors at the top of the form so I'm passing the error object back to the ejs template:

<% if (error) { %>
   <li><%= error %></li>  
<% } %>

But when I initially load the page and there are no errors yet (because the form has not been submitted) I'm receiving an error on the page and the form is not rendered:

error is not defined

How can I get around this?

like image 947
Mike Rifgin Avatar asked May 06 '26 12:05

Mike Rifgin


1 Answers

You can do that check in three ways :-

  • Using the method suggested by Amit :

res.render('registration', {error: false});

  • Check to see if error exists like this :

<% if( typeof(error) =="undefined")%> //checks the type of variable

  • You can see if the variable error exists by accessing the locals object like this :

<% if(locals.error) %>

like image 139
Natesh bhat Avatar answered May 10 '26 02:05

Natesh bhat