When using res.render to pass data to an EJS file and accessing it in plain JavaScript

I'm currently working on an Express GET function where I am sending data to an EJS file using the res.render() function. My question is, how can I access this data in plain JavaScript within the same EJS file? Here is my GET Function:

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 here's an example of how I'd like to use the data:

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

Answer №1

The concept of EJS Tags can be broken down into three main categories.

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

<% As server side scripts, these tags will not produce any output visible to the user. %> 

<%- Used for injecting unsanitized JavaScript values directly into your HTML code, allowing you to include HTML this way. %>

<%= When using these tags, JavaScript values are sanitized before being injected into your HTML, displaying HTML tags as strings. %>

To log messages in the browser console, you can utilize...

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

If you prefer logging to the server side console, simply use...

<% console.log(votes); %>

Answer №2

Remember, when working with expressions in your code, it's important to use <%= votes %> rather than <% %> tags as they do not evaluate the expression correctly.

Answer №3

Consider utilizing <%- votes -%>, it has proven effective for my needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can someone explain why the console.log(items) command seems to be executing twice

Item.find() .then(function (items) { if (items.length === 0) { Item.insertMany(defaultItems) .then(function () { console.log("Successfully Saved"); }) .catch(function (err) { console.l ...

How can Node / Javascript import various modules depending on the intended platform?

Is there a way to specify which modules my app should import based on the target platform in TypeScript? I am interested in importing different implementations of the same interface for a browser and for Node.js. In C++, we have something like: #ifdef wi ...

The asynchronous times function fails to trigger the callback

I'm currently working on implementing async into my project. What I am trying to achieve is creating and saving multiple objects using mongoose, and then receiving a callback once the task is completed. Despite successfully saving the objects in the ...

Using AngularJS to filter search results based on two user-provided input parameters

Currently, I am working on an Angular application that presents movies in a table format with search input and dropdown filter by genres. As I work on this project, my main focus is finding a way to filter search results based on both the text entered in t ...

Using regular JavaScript with code inside ng-view in AngularJS involves incorporating event listeners and manipulations that can interact

Just delving into the world of angularJS for the first time. I've set up the routing service, which involves having a div with routing that calls in a template containing HTML code. I also have a range of regular JavaScript functions necessary for the ...

Demonstration of using .queue() and .dequeue() in relation to $.queue() and $.dequeue()

I successfully completed an animation using animate(), queue(), and dequeue(). However, I recently discovered that jQuery also offers jquery.queue() or $.queue() and jquery.dequeue() or $.dequeue(). Can anyone assist me in understanding these new terms w ...

I am in need of a blank selection option using an md-select element, and I specifically do not want it to be

I'm currently utilizing Angular Material with md-select and I am in need of creating a blank option that, when selected, results in no value being displayed in the select dropdown. If this blank option is set as required, I would like it to return fal ...

Using the class method to handle jQuery events alters the context

Is it possible to access the class context from within a method being used as a jQuery event handler? The example below illustrates the scenario: class EventHandler { constructor() { this.msg = 'I am the event handler'; } ...

Utilizing AngularJS to extract data from a query string

After making significant progress on my previous project, I found myself in need of some final assistance that has proven to be elusive. I successfully built my entire angular controller and populated all the necessary data for the page. However, I am str ...

What is the best way to compare an attribute value with a JSON value in JavaScript?

I have a JSON string that looks like this: { "DocID": "NA2", "DocType": "Phase1.1 - Visa Documents (This section is applicable for HK work location only)", "DocSubType": "New Application", "DocName": "Passport / Travel Document (Soft copy only) ...

Importing images with relative paths from a JSON file does not work as expected in Next.js

JSON file data portion: { "categories": [ { "id": 1, "category_slug": "food_supplements", "title": "Food Supplements", "image": "/../../public/images/foodSupplements.png", } ] } Component data portion that displays the ...

The editMessageReplyMarkup function does not support inline keyboards and will remove them from the

Currently, I am developing a telegram bot using the node.js platform along with the node-telegram-bot-api library. One particular issue I am facing is related to responding to callback_query events and updating the inline keyboard simultaneously. The cod ...

Trouble arises when trying to configure webpack and install npm packages on Ubuntu systems

Recently, I encountered a sudden issue in my project that caused it to repeat and crash in Chrome: https://i.stack.imgur.com/pkVlA.png To resolve the issue, I decided to downgrade some of my packages and also downgraded my npm version to 6.6.0 which prov ...

find the middle element in the Vue array

Currently in the process of developing a custom Vue carousel component, I have utilized some code snippets from this resource: link My goal right now is to enhance the slider with additional navigation bullets. However, due to the justify-content:center p ...

What is the method for adding an event listener in AngularJS within an ng-repeat iteration?

I'm completely new to AngularJS and currently working on building a photo gallery. The basic idea is to have an initial page displaying thumbnail photos from Twitter and Instagram using an AngularJS ng-repeat loop. When a user hovers over an image, I ...

Passing variables dynamically in a created Express.js route

Creating routes in Express.js from a JSON file with the specified structure: { "/home":{ "token":"ksdjfglkas" }, "/logout":{ "token":"ksdjfglksaudhf" } } It is necessary to access the token within the routes function. The JavaScript code ...

Angular 2 does not recognize the element 'child-selector' as valid

In my quest to establish communication from a child component to a parent component based on certain actions, I have incorporated the use of both EventEmitter and Output libraries. Let me walk you through what I have achieved thus far. Firstly, let's ...

Having trouble with a JQuery selector not functioning properly when trying to select a class in the HTML that contains a

Looking for help with a JQuery selector to target the title of a YouTube video. Here's the HTML snippet: <div class="ytp-title-text"> <a class="ytp-title-link yt-uix-sessionlink" tabindex="13" target="_blank" ...

Nodemon is not compatible with Ubuntu operating systems

I am currently running ubuntu and have node 12.6 npm 6.13 installed. After using the command npm i -g nodemon I was able to successfully install nodemon. + <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="244a4b4041494b4a6416 ...

Encountering issues when trying to publish to MongoDB

Hi everyone, I am a beginner in MEAN stack development and I'm facing an issue while trying to make a post request using Postman. The error message I'm getting is "username not defined". I have successfully established a connection with mongodb a ...