2

Ultimately I'm trying to pass JSON data from the Node server to be used by D3 in the client.

Here's my index.js

var express = require('express');
var router = express.Router();

var portmix = require('../data/holdings.json');

/* GET individual portfolio page. */
router.get('/portfolio/:portcode', function(req, res) {

  var porthold = [];
  for(var i in portmix){
    if(portmix[i].PortfolioBaseCode === req.params.portcode){
        porthold.push(portmix[i])
  }}

  res.render('index', { 
    pagetype: 'single_portfolio',
    holdings: porthold[0]
  });
});

module.exports = router;

Here's the ejs file:

<div class="portfolio">

    <h2><%= holdings.ReportHeading1 %></h2>
    <ul>
        <li>Cash: <%= holdings.CashMV %></li>
        <li>Fixed Income: <%= holdings.FixedMV %></li>
        <li>Equity: <%= holdings.EquityMV %></li>
        <li>Alternatives: <%= holdings.AltMV %></li>
    </ul>

    <div class="chart">
    </div>
</div> 

It works to display the "holdings" values. However, if I try to call it from a client side js using:

console.log("Holdings: " + holdings);

The result is

Holdings: undefined

Is there a way to do this? Or am I going about it all wrong?

1

1 Answer 1

3

You can't call the EJS variables from the clientside, you have to output the JSON to the page, and then fetch it

<script type="text/javascript">

   var json_data = <%- JSON.stringify( holdings ); %>

   // use the above variable in D3

</script>

<div class="portfolio">

    <h2><%= holdings.ReportHeading1 %></h2>
    <ul>
        <li>Cash: <%= holdings.CashMV %></li>
        <li>Fixed Income: <%= holdings.FixedMV %></li>
        <li>Equity: <%= holdings.EquityMV %></li>
        <li>Alternatives: <%= holdings.AltMV %></li>
    </ul>

    <div class="chart">
    </div>
</div> 
Sign up to request clarification or add additional context in comments.

2 Comments

This was close. In order for it to work I had to change it to <%- JSON.stringify( holdings ) %>
@jtmcn - oh, that's right, otherwise it would escape the quotes

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.