0

I want to access a JSON array inside the script tag of a EJS file. I'm passing the JSON array from my index.js file to the EJS file while rendering it. The code is:

sampleJArr=["data1","data2","data3"];
app.get('/test', function(req,res){
res.render('testfile',{
 'mJsonArr': sampleJArr
});

In the EJS file (testfile.ejs), code-:

<div>
  <!--Printing the JSON array. It prints  -->
  <p>JSON.stringify(mJsonArr)</p>
  <button onClick="myFunc">Take test</button>
</div>
<script>
  function myFunc(){
    var JsonData= <%= mJsonArr[0] %>
    console.log(JsonData)
  }
</script>

Error:-Uncaught ReferenceError: myFunc is not defined at HTMLButtonElement.onclick

But when I'm trying to do a console("some string") inside myFunc then it's not giving that error. Only when I'm accessing mJsonArr inside the script tag, I'm getting UncaughtRefrence error. How can I access the passed mJsonArr inside my script tag ? Please contribute. Thankyou.

1 Answer 1

1

The reason why you can not access mJsonArr[0] in your script tag is because EJS just replace <%= mJsonArr[0] %> to data1 which means your generated html will be like

<div>
  <!--Printing the JSON array. It prints  -->
  <p>JSON.stringify(mJsonArr)</p>
  <button onClick="myFunc">Take test</button>
</div>
<script>
  function myFunc(){
    var JsonData= data1
    console.log(JsonData)
  }
</script>

In which there are 2 points are wrong

  1. onClick="myFunc"

This need to be changed to onClick="myFunc()". Otherwise it will never invoke.

  1. var JsonData= data1

This is not assigning a string value 'data1' to variable. It is assigning a value of a variable named 'data1' to variable JsonData.

The correct way to do this should be

<div>
  <!--Printing the JSON array. It prints  -->
  <p>JSON.stringify(mJsonArr)</p>
  <button onClick="myFunc()">Take test</button>
</div>
<script>
  function myFunc(){
    var JsonData= '<%= mJsonArr[0] %>'
    console.log(JsonData)
  }
</script>

Hope it can help you

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks man, it worked perfectly. I got your explanation too :)
Glad I can help. If possible please mark my answer as correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.