0

I am trying to pass some JSON data from an express route to a .js file which is in a .pug template. I can't figure out how to achieve this. I am trying as follows:

The router:

// Office Locations
router.get('/office_locations', (req, res, next) => {
  var sql = 'SELECT * FROM office_locations ORDER BY oloffice';
  var params = [];
  pool.query(sql, params, (err, result) => {
    if (err) {
      console.log(err);
      res.json(err);
    } else {
      res.render('office_locations', {title: title, tabledata: JSON.stringify(result.rows)});
    }
  });
});

The PUG file:

extends layout

block content
  .container
    include menu.pug
    .workspace
      .map-content
        .map#map


  include main-addons.pug

  link(rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA==" crossorigin="")
  script(src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg==" crossorigin="")
  script(src="/javascripts/office_locations.js")
  script(src="/javascripts-dev/table.js")

The file where I require the tabledata information is table.js:

$(document).ready(function() {
  // get the table data
  var tabledata = !{tabledata};
  console.log(tabledata);
});

But am getting always false when logging to console.

How can this be achieved?

1 Answer 1

1

Add this code before the script(src="/javascripts-dev/table.js") line:

 script(type='text/javascript').
   window.tabledata = "#{tabledata}";
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Just figured it out that I needed to use a window variable.

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.