illla
illla

Reputation: 105

How to send the data from .ejs file to .js file?

To send the data to .ejs file, we use res.render() method. Now if that .ejs file has some .js file in script tag, how can we send the same data to .js file?

// Server file contains
app.get('/student/data_structures/mock_test_1', (req, res) => {
   res.render('student/mock_test', { questions });
})

questions is an array of objects

// mock_test.ejs contains
<script src="../../static/dom.js"></script>
        

In mock_test.ejs file I have access to questions, the question is how to have access to questions in dom.js?

Upvotes: 3

Views: 1857

Answers (1)

EXV
EXV

Reputation: 41

Here: https://stackoverflow.com/a/38180679/15274869

in your mock_test.ejs:

<script>
    const questions = <%- JSON.stringify(questions) %>
</script>
<script src="../../static/dom.js"></script>

(Ignore "Expression expected" editor errors if you get any.)

The variable questions holding an array is then readily available in dom.js.

Upvotes: 3

Related Questions