0

There are a log of question on JavaScript scope, but none that address my exact issue.

How do I access the user object inside my script, and why is it not visible?
My app renders a .ejs page. Consider the following code:

<html>
<body>
     ...some stuff
     <% if (user.local.email) { %>      <!-- WORKS PERFECTLY -->
     ... some stuff
     <% } %>
     <script>
         $(document).ready(function() {
         console.log(user);            //-- DOES NOT WORK
         }                             //-- REFERENCE ERROR: USER NOT DEFINED
     </script>
</body>
</html>

I don't understand why user is visible in one part of the page, but not in the script below it?

Dirk
  • 3,073
  • 4
  • 31
  • 36
  • 2
    Because `user` isn't a JavaScript variable - it's written in from the server. You need to understand the difference between client and server. – tymeJV Jul 15 '15 at 14:43

2 Answers2

0

The answer is nicely explained here

In essence, from that answer, you capture the value:

<script type='text/javascript'>
   var rows =<%-JSON.stringify(data)%>
</script>
Community
  • 1
  • 1
Dirk
  • 3,073
  • 4
  • 31
  • 36
0

EJS is used for Server-side scripting and JavaScript is used for Client-side scripting. So one's variables aren't available in another. EJS is executed on the server and all variables declared are gone after execution. Then the page is returned to the browser and the browser executes Javascript afterwards, so EJS variables are not available within Javascript.

However, if you want to do this then you can do:

console.log(<%= user %>);

Hope that answers your question.

Abraar Arique Diganto
  • 1,215
  • 16
  • 24