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?

jtmcn
  • 317
  • 1
  • 3
  • 8
  • possible duplicate of [Pass variables to JavaScript in ExpressJS](http://stackoverflow.com/questions/16098397/pass-variables-to-javascript-in-expressjs) – Rahil Wazir Jan 05 '15 at 20:21

1 Answers1

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> 
adeneo
  • 312,895
  • 29
  • 395
  • 388