0

I have this next GET function in express and in the res.render() function i'm sending to the EJS file the data i want to use, now my question is how can i use the data that i've sent to the EJS file in plain javascript in the same EJS file? GET Funtion:

router.get('/:id', (req, res) => {
	let pollId = req.params.id;
	Poll.findById(pollId, (err, poll) => {
		if(err) throw err;
		Vote.find(pollId, (err, votes) => {
			res.render('vote', {user: req.user, poll: poll, voteFail: req.flash('voteFail'),votes: votes });
		});
	});
});

And an example of how i want to use the data:

<script type="text/javascript">
  console.log(<%votes%>);
</script>

3 Answers 3

3

There are three main EJS Tags

<% %> and <%- %> and <%= %>

<% These will run script server side - There is no output - The user will not see this %> 

<%- These will inject javascript value into your html, unsanitized - you can pass html this way. %>

<%= These tags will inject the javascript value into your html, sanitized - html tags will appear as strings %>

If you want to console log in the browser console you can use...

<script>
   console.log( <%-votes%> );
</script>

If you want to console.log to the server side console simply use...

<% console.log(votes); %>
Sign up to request clarification or add additional context in comments.

Comments

0

Using <% %> tags does not evaluate the expression. Use <%= votes %> instead.

3 Comments

It returns in the browser console this: Uncaught SyntaxError: Invalid or unexpected token
@WackThat Not sure what you're trying to do in the end but in this particular scenario you could do <% console.log(votes)%> without the <script> tags and it should work.
I'm trying to use the data to make a Chart.js graph. you can do that only in plain js.
0

Try using <%- votes -%>, works for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.