Passing data from Node js to HTML using EJS
changing it to <%= name %>
should fix it.
If that doesn't you can try changing app.set('view engine', 'html')
to app.set('view engine', 'ejs');
, then deleting the following 2 lines.
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
app.get('/',function(req,res){
var title = "PERFORMANCE OVERVIEW" ;
res.render('Main',{name:title}) ;
});
I have always written it this way, so I can't say for sure if you syntax is correct, or if ejs will even work without setting it like this.
Update
Make sure the Main.html
file is in a folder called views
, and rename this file to Main.ejs
.
next change res.render('Main.html',{name:title});
to res.render('main',{name:title});
How to pass data from express to ejs
you are missing a "="
<%= data %>
and you have to iterate through data as its not a single data and if you wanna print a single data then pass only one data
res.render('pages/tasks', {data: results.rows[0]});
Pass Data From Node/Express to Front-End Javascript
You can't respond to a single request with both an HTML document and a seperate JavaScript file.
So you need to either:
- Store the data somewhere and, in a separate endpoint, serve up some generated JavaScript and have a mechanism which identifies which data to serve up when the request is made. (NB: This is stupidly complex. Don't do it.)
- Generate the JavaScript inline in the HTML document inside a
<script>
element. (You'll need to properly escape the data as JS to make sure you aren't subject to XSS). - Output the data into the HTML document (e.g. with
data-*
attributes or<meta>
elements) and read it with static JavaScript. - Again, using a seperate endpoint: Serve up JSON with the data in it and read that with Ajax from a static JS file. (Again, you'll need a way to determine which data to send for that particular request).
How to use a passed variable in an ejs file
If I got it right, you are trying to insert the value of the EJS variable in the HTML tag from JavaScript when the user clicks the checkbox.
The value of the HTML tag doesn't change because in your JS code:
document.querySelector('.plan-title').innerHTML = investment.name;
document.querySelector('.plan-description').innerHTML = investment.description;
investment.name
and investment.description
are undefined. Check the console on your page.
This is because you tried accessing EJS variables after the page finished rendering.
EJS is mainly used to pass server-side variables to the page before it is rendered. So once it's rendered you cannot access those variables.
So to have the values of those variables in your JavaScript after the page finishes rendering, try doing:
document.querySelector('.plan-title').innerHTML = '<%- investment.name %>';
document.querySelector('.plan-description').innerHTML = '<%- investment.description %>';
instead. This is how you pass the EJS variable to JavaScript. JavaScript now sees it as a string and there's no problem, unlike in your code where it was looking for investment
object and returned undefined since that variable is not defined on the client-side.
Also, since you have a for-each loop in the HTML part, I'm assuming you are trying to change the values of specific plan-title
and plan-description
divs. If that's the case, '<%= investment.name %>'
and '<%= investment.description %>'
in JavaScript part should be in a for-each loop as well, but that would be a lot of mess.
I suggest you instead to right under the for-each loop in the HTML part, add class to the div tag according to the index of the for-each loop, add on change event to the checkbox, and pass the checkbox and the index of the for-each loop to the JavaScript function which would handle the on change event, include the EJS variables in the plan-title
and plan-description
divs, and in the JavaScript function that handles on change event change the CSS display property from display: none
to display: block
to these divs.
See an example:
HTML:
<% investments.forEach((investment, index)=>{ %>
<div class="col-md-4">
<div class="card">
<strong>
<%= investment.name %>
</strong>
<h4>
<%= investment.min %> - <%=investment.max %>
</h4>
<p>
<%= investment.caption %>
</p>
<p><input onchange="displayPlan(this, '<%= index %>')" type="checkbox" name="plan" id="">Choose investment</p>
</div>
<% if(currentUser && currentUser.isAdmin){ %>
<a href="/investment/<%= investment._id %>/edit">Edit</a>
<a href="/investment/new">Delete</a>
<% } %>
</div>
<% }) %>
<% investments.forEach((investment, index)=>{ %>
<div class="plan <%= index %>" style="display: none;">
<div><strong>Package: </strong>
<p class="plan-title">
<%- investment.name %>
</p>
</div>
<p class="plan-description">
<%- investment.description %>
</p>
<input type="number" name="" id="" min="<%= investment.min %>"
max="<%= investment.max %>">
</div>
<% }) %>
JavaScript:
function displayPlan(checkbox, id){
if (checkbox.checked) {
document.querySelector(`.plan.${id}`).style.display = 'block';
}
else {
document.querySelector(`.plan.${id}`).style.display = 'none';
}
}
Cheers!
EDIT: Grammar and syntax issues
Related Topics
Javascript Add Class Active When Click a Link After Load Another Page
How to Let a User Download Multiple Files When a Button Is Clicked
Recursively Find Keys on an Object
How to Add Counter in Angular 6
Why Isnt Window.Location.Href= Not Forwarding to Page Using Safari
Jquery Ajax Readystate 0 Responsetext Status 0 Statustext Error
Sequelize - How to Return Json Objects of the Database Results Only
Syntaxerror: Cannot Use Import Statement Outside a Module
Javascript Function (Input Date Bigger Than Today Date)
Element Implicitly Has an 'Any' Type Because Index Expression Is Not of Type 'Number' [7015]
Why Am I Not Able to Add Input Text into My Table
Javascript Dashes in Phone Number
Can Vue-Router Open a Link in a New Tab
How to Set Profile Image as First Letters of First and Last Name
Form Builder - Cannot Read Property 'Get' of Undefined, Issue With Validators