1

I am using Jade framework as frontend with Nodejs & express for backend

so when I am rendering a view with data i can't access these data using JQuery

below my service from Nodejs that renders a view with simple data = x

router.get('/test',function (req,res,next) { res.render('test',{data : 'x'}); }); 

so the test page will show without any problem, what am trying to do is to read the rendered data using Jquery methods

 footer .pull-right | Gentelella - Bootstrap Admin Template by a(href='https://colorlib.com') Colorlib .clearfix // /footer content // jQuery script(src='/vendors/jquery/dist/jquery.min.js') alert(data) // no alert or action happen 

but the error said (unknown variable of data)

Moreover, I can read it from jade itself

any suggestions?

thank you

1 Answer 1

1

Try using the following

|<script> !='alert("'+data+'")' |</script> 

The JavaScript you are writing inside your jade framework will not be able to see your server side node.js variables because this client side JavaScript is loaded and executed inside the browser, so you have to pass your variables somehow from the server side to client side then obtain these variables using client side JavaScript.

If you are passing some strings , it is easier for you to use the previous way.

|<script> -> open the JavaScript tag.

!='alert("'+data+'")' -> normal jade string that will be inside our JavaScript tag , that means it should give us JavaScript code after being processed by jade which will make our final text alert("x") because data will be replaced by its value.

|</script> -> close The JavaScript tag

but if you want to pass object there are a ways to do so :

  • Using AJAX requests.
  • Use JSON.stringify(data) in server side to write your object to a hidden div and in client side using var data = JSON.parse(jQuery('div').text())
Sign up to request clarification or add additional context in comments.

4 Comments

unfortunately didn't read the data and below the error profile:2 Uncaught ReferenceError: data is not defined at profile:2
modified my answer , try it now
oh wow it's working now !! but the problem is u tried to add my own code but couldn't !!! I tried to duplicate your code also can't | <script type='text/javascript'> !='alert("' + services + '")' !='alert("' + services + '")' | </script> so what is the secret here ??
added some explanation in my answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.