user8142459
user8142459

Reputation:

res.render send data to EJS file and using it in plain javascript

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>

Upvotes: 0

Views: 7346

Answers (3)

CopyPasteThankYou
CopyPasteThankYou

Reputation: 85

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); %>

Upvotes: 3

Shahrukh Anwar
Shahrukh Anwar

Reputation: 2632

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

Upvotes: 0

David
David

Reputation: 971

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

Upvotes: 0

Related Questions