0

I want to capture the value from a variable that it is sent from NodeJS route to a view. I know that the way to get this value on HTML (Jade) is:

#{name_var}

But I want to get this value in JS (JQuery) and the only way that I can think is by DOM (for example: create a div with this value that it is hidden and later, get the value by getElementById).

But I think that this data that I send to the view are delicated, it could be have a great security problem...

What do you think? Are there any other 'alternative' for this? Thank you.

danigonlinea
  • 1,113
  • 1
  • 14
  • 20

1 Answers1

2

I think you dont want to go through the hard way of putting the value first to a dom element and fetch it later to process.

You can directly assign the values to js variable like the same way you did in your html tags.

Like

script(type='text/javascript').
    var somevar = "#{serversideValue}";

So that while the html is rendered out of the jade template, it will be rendered as

script(type='text/javascript').
    var somevar = "passedValue";

Also according to the value passed from the router, you can choose whether to use html encoding or not while assigning the value to the js variable like #{serversideValue} or !{serversideValue}.

Also if you are passing a complete json object via the router variable, then you cannot directly assign it like what we seen above. One way is to JSON.stringify() the value when you send it from the router and use JSON.parse() in clientside JS to get back the original object.

Also You might want to look at this stackoverflow question to get an understanding of the scenario that we discussed now.

Community
  • 1
  • 1
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
  • Perfect. It works in the HTML file. You missed something: you have to add a dot to the end of the first line. A want to ask something more... I have checked this code to add it in JQuery (inside $document.ready()) and it is not work because Jquery don't get the value... just convert "#{serversideValue}" as a String. This is not important but I want to know if this is possible. Thank you very much. – danigonlinea Oct 04 '14 at 12:11
  • just check the html source in browser, it should have rendered the value or are you saying it still comes as `"#{serversideValue}"` there? Jquery doesnt make any difference to the case here. – Mithun Satheesh Oct 04 '14 at 12:17