-2

I have a rather strange problem. On server side, I call an an ejs-page by

res.render('index', {varArray: JSON.parse(response)});

When I try to use the variable "varArray" within HTML-Code, everything works fine, e.g.:

<% for (var i = 0; i < varArray.length; i++) { %>
    <option value="<%= varArray[i].id %>"><%= varArray[i].name %></option>
<% } %>

BUT: As soon as I want to use the same variable in a function on the same page, I get an error message, that this variable is undefined.

<body>
<script>
function test() {
  for (var i = 0; i < varArray.length; i++) {
// do something
  }
};
</script>

I hope, someone can help me.

Mike
  • 3
  • 3
  • 3
    It looks like you're trying to mix client-side and server-side code. Code that runs on the client has no access to variables declared on the server. – Kevin B Feb 26 '19 at 21:39
  • Put it somewhere in the DOM (like a hidden input) and pull the value out at runtime. You're trying to mix client and server runtimes. – zero298 Feb 26 '19 at 21:41
  • to do client side manipulation, you should really invest some time in Vue.js, Angular, or React. These are all frameworks that will allow you to integrate JS code w/ the DOM (not the way you have it, of course). – LostJon Feb 26 '19 at 21:47
  • Possible duplicate of [passing an array from EJS to Javascript](https://stackoverflow.com/questions/38179668/passing-an-array-from-ejs-to-javascript) – cantuket Feb 26 '19 at 22:03

1 Answers1

-1

Unfortunately I can't test this in ejs, but if its a JavaScript Array you could...

  1. JSON.stringify() the variable,
  2. print string to the dom
  3. Assign it to a variable within the desired scope.

<% for (var i = 0; i < varArray.length; i++) { %>
    <option value="<%= varArray[i].id %>"><%= varArray[i].name %></option>
<% } %>

<script>
var varArray = <%= JSON.stringify(varArray) %>;

function test() {
  for (var i = 0; i < varArray.length; i++) {
// do something
  }
};
</script>

If the test() function isn't rendered through ejs then you could assign it to the Global object (window) then use it anywhere after it's been defined...

<% for (var i = 0; i < varArray.length; i++) { %>
    <option value="<%= varArray[i].id %>"><%= varArray[i].name %></option>
<% } %>

<script>
window.varArray = <%= JSON.stringify(varArray) %>;
</script>

<script>
function test() {
  for (var i = 0; i < varArray.length; i++) {
// do something
  }
};
</script>
cantuket
  • 1,582
  • 10
  • 19
  • That helped me a lot ! Finally I found with your help, that I have to transfer the "varArray" as a parameter to the function. It is not globally accessible. – Mike Mar 02 '19 at 16:36
  • Great glad I could help! If this is your "accepted" remember to mark it as such at some point – cantuket Mar 02 '19 at 17:36