Faisal
Faisal

Reputation: 441

JQuery & jade read render data from Nodejs

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

Upvotes: 1

Views: 992

Answers (1)

Ezzat
Ezzat

Reputation: 911

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())

Upvotes: 1

Related Questions