Skip to content
Advertisement

trying to send some data from nodejs to script in html

I am using hbs as view in frontend. I tried to send data to my script in html from nodejs like this :

router.get('/home',authController.isLoggedIn, (req ,res) => {
if(req.user){
    db.query('SELECT * FROM posts ORDER BY id desc ', (error,results) => {
        if (error) {
            console.log(error);
        } else {
            let categories;
            db.query('SELECT * FROM categories', (error,result) => {
                if (error) {
                    console.log(error);
                } else {
                    console.log(result);
                    categories = result;
                    return res.render('home',{
                        results: results,
                        categories: categories
                    });
                }
            });
        }
    });
}else {
    res.redirect('/login');
}

});

then when i am trying to call it here in script using javaScript it tells me something is wrong

<script>
        alert(results);
 </script>

I want to know how correctly call the the object in script

edit:

the data should be something like this :

  [
  RowDataPacket { id: 1, category: 'Music' },
  RowDataPacket { id: 2, category: 'Memes' },
  RowDataPacket { id: 3, category: 'Tech' }
  ]

Advertisement

Answer

For EJS example if pass data msgs:

    res.render("index.ejs", { 
        msgs
     })
  1. js handle data:
    <p>
        <% 
            msgs = msgs.map(function(msg) {
                return '<div>' + msg.name + '</div>' + '<div>' + msg.msg + '</div>'+ '<div>' + msg.time + '</div>'
            }) 
        %>
    </p>
  1. print directly:
    <p><%- msgs.join("<hr />") %></p>
  1. save in global variable
    <script>
        window.serverMsgs = <%- msgs %>;
    </script>

And for handlebars:

    <script>
        window.serverMsgs = {{msgs}};
        alert(window.serverMsgs)


        {{#each results}}
                {
                    "id": {{id}},
                    "category": "{{category}}",
                }
                {{#unless @last}},{{/unless}}
        {{/each}}

    </script>
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{{title}} - Page Test</title>
</head>
<body>
    <div class="description">{{description}}</div>
    <ul>
{{#datas}}
        <li class="item" id="item_{{index}}"><span>{{time}}</span><a href="{{url}}" class="art">{{title}}</a></li>
{{/datas}}
    </ul>

</body>
</html>

u could check out this similar issue:) How to define an array within a <script> tag inside a hbs view template

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement