2

Short version: A variable is stored in a session variable req.session.userName and also in the json sent with res.render('/', {username: value}). How can I access either of those variables from inside client side javascript?(inside the script tags in the html)


MORE INFO: In my express&node webapp, a user has logged in from a separate login page. I have stored the username in a express-session variable: req.session.userName. I have redirected the page back to the main page which will call this:

router.get('/', function(req, res) {
    res.render('index', { title: 'Title of webpage', user: req.session.userName});
});

I would now like to alter parts of the html page based on the contents of the variable 'user' such as changing the sign in button to sign out and writing a welcome message to the user.

I understand that html can make use of that variable like so:

<%- user %>

However i need access to it in the client side script of my main page(html). Can JQuery make use of that json variable or session variable somehow like the following?(e.g. ask it if its undefined? use the contents of it to manip html elements?)

<script>
    $(function(){
        $("#welcome").html("Welcome, " + **user**);

        if (**user** == undefined){
            //do something
        }
    });
</script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.