How do I use data from the server side on the cliente side?

Viewed 41

This is my app.js

var products = [
   {description: "Hi"},
   {description: "Hi2"}
]

app.get('/', function (req, res){
    res.render("home.ejs");
})

app.get('/checkout', function (req, res){
    res.render('checkout.ejs', {products:products});
});

app.post('/checkout', function(req, res){

    var description = req.body.description;
    var newProduct = {description};
    products.push(newProduct);

    res.redirect('/');
});

This is my home.ejs

<form action="/checkout" method = "POST">
                    <p class = "item-description">LP Snake Pocket Tee</p>
                    <input type="hidden" name = "description" class = "item-description-post">
                    <div class="btn-group btn-add mr-2" role="group" aria-label="Second group">
                        <button class="btn btn-success btn-add-cart">ADD TO CART</button>
                    </div>
</form>

And this is my hoje.js file, which just basically fills my input value with what I want, so I can send that as POST input

var item = $(".item-description")[0].innerHTML;
var postInput = $(".item-description-post").val(item);

Now I'm my checkout.ejs file I can do something like this, and print all my products (descriptions only so far)

                <% products.forEach(function(product){ %>
                    <p> <%= product.description %> </p>
                <% }); %>

My question is, how can I do the same thing, but in a separate .js file?

I do have a javascript file connected with my checkout.ejs

<!-- JAVASCRIPT -->
<script type = "text/javascript" src="./checkout.js"></script>

But that file can not access my array 'products'. Which makes sense, because my back end is only sending that data to my ejs file, so basically, how do I send that data 'products' from my app.js file to my checkout.js file? :)))

1 Answers

You can't.

Note: You can only pass data from .ejs file to .js file but not the other way. It won't work because .ejs is rendered on the server side while .js runs on the client side. I am assuming you are using EJS on server side Why:

The EJS template will be rendered on the server before the js is started execution(it will start on browser), so there is no way going back to server and ask for some previous changes on the page which is already sent to the browser.

Related