Ishaan Shakunt Ishaan Shakunt -4 years ago 46
MySQL Question

Part of my js script not working in my ejs file

The "if" statement in my ejs file doesn't seem to work.

Here is my .ejs file:



<!DOCTYPE html>
<html>
<head>
<title>causelist</title>
</head>
<body>
<h1>Select the causes you want to back.</h1>
<form action="/causelist" method="post">
<% cause.forEach(function(cause){ %>
<input type="checkbox" name="cause" value="<%= cause.CauseId %>" <% if (cause.CauseId===donate.CauseId1 || cause.CauseId===donate.CauseId2 || cause.CauseId===donate.CauseId3 || cause.CauseId===donate.CauseId4 || cause.CauseId===donate.CauseId5) { %> checked <% } %> > <%= cause.CauseName %> <br>
<% }) %>
<input type='submit'>
</form>
</body>
</html>





Here is my app.get which renders the page and sends in values after retrieving from my MySQL DB:

app.get('/causelist', ensureAuthenticated, function(req,res){
connection.query("select * from DonateTo where UserId = "+ req.user.UserId, function(err,rows){
if(err) console.log(err);
var donate = rows;
console.log("donate:"+ donate);
connection.query("SELECT * FROM Causes",function(err,rows){
var cause = rows;
console.log("cause:"+ cause);
res.render('causelist',{cause,donate});
if(err)
console.log(err);
});
});
});


I don't understand what I'm missing.

Note: Except the if statement, the rest of the code works fine. i.e. data being retrieved from my DB is correct.

Answer Source

that is because you send a json array named cause then in .ejs file you parse it correctly and take objects from this but donate is an json array and if you want get property from its objects you should define which object do you want with index so if you want the first object from donate you should send it to client like donate[0]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download