0

I wrote my own JavaScript function inside an ejs file which I want to use it inside that file. The problem is that it is not working because the function is declared to be undefined . I have declared that function inside the ejs file as illustrated below.

//my ejs file
<script> 
        function c_tab (){
            //codes...
            return "data";
         }

    </script>
</head>
<body>
    <h1>WELCOME  TO  E J S </h1>
     <p>Ok this willrecievedata from server ... <%=  c_tab(); %> 
    </p>

The error report says that c_tab is not defined

So how to use a user defined javascript function inside ejs file .

norbitrial
  • 14,716
  • 7
  • 32
  • 59
GNETO DOMINIQUE
  • 628
  • 10
  • 19

2 Answers2

1

Well, the basic answer to your question is probably

<%
    var foo = function(){return 'bar'};
%>
<body>
    <h1>WELCOME  TO  E J S </h1>
     <p>Ok this will recieve data from server ... <%=  foo(); %> 
    </p>
</body>

but since you said "receive data from the server" in your code, I presume you are passing local variables from express to ejs via .render()

In that case the variables should just be available, but you want them available in your client side code. Try something like

<script>
  var foo = <%= JSON.stringify(bar_obj_from_server)%>
  var fooString = '<%= bar_str_from_server %>'
<script>
Cody G
  • 8,368
  • 2
  • 35
  • 50
0

Use Scriptlet tag instead of script tag:

<% 
        function c_tab (){
            //codes...
            return "data";
        }
%>
Ashish Kumar
  • 401
  • 4
  • 11