0

I am trying to load data from the server in my pug template.

My route looks like the following:

app.get('/serverdata', async(req, res) => {

  const chartData = []
  for (const i = 0; i < 7; i++) {
    chartData.push(Math.random() * 50)
  }

  const result = JSON.stringify(chartData)

  res.render('serverdata', {
    result,
  })
})

My pug template looks like the following:

  .row
    .col-md-12
      .card
        .embed-responsive.embed-responsive-16by9
          canvas#myNewChart(style='display: block; width: 1000px; height: 500px;', width='1000', height='500')      

block specific-js
  script(type='text/javascript', src="js/plugins/chart.js") 
  script(type='text/javascript').
    var data = {
      labels: ["January", "February", "March", "April", "May", "June", "July"],
      datasets: [
        {
          label: "My First dataset",
          fillColor: "rgba(220,220,220,0.2)",
          strokeColor: "rgba(220,220,220,1)",
          pointColor: "rgba(220,220,220,1)",
          pointStrokeColor: "#fff",
          pointHighlightFill: "#fff",
          pointHighlightStroke: "rgba(220,220,220,1)",
          data: result //here I am getting the error
        }
      ]
    };

    var ctx = document.getElementById("myChart").getContext("2d");
    var myNewChart = new Chart(ctx).Line(data);

My error is within my view file:

serverdata:13 Uncaught ReferenceError: result is not defined
    at serverdata:13

Any suggestions how to load server data in the script. tag of my pug file?

I appreciate your replies!

1
  • 1
    The res.render should look like this res.render('serverdata', { result: result }) and i think(i'm not using pug myself) that in your pug file you should use #{ result } Commented Nov 5, 2017 at 8:59

1 Answer 1

1

I think you are mixing different contexts. The line that gives you an error is executed in the browser, and in that context, there is no variable named result.

Since you have a endpoint /serverdata on your server in place, all you need to load and parse the data from that URL. Details depend on what kinds of JavaScript libraries you are using, but with jQuery getJSON:

$.getJSON("/serverdata", function(data) {
    /* Update your chart by using 'data' */
});
Sign up to request clarification or add additional context in comments.

Comments

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.