1

I am learning node and javascript and need your help in using javascript variable in my EJS file.

On page load, I am making an ajax call to get me some values. I want to display that on the page once the call is successful.

Please find my EJS code below.

<div id="tab2" class="tab">
    Page 2 am in friends page
    <script type="text/javascript">
        if (currentFriend) { // currentFriend is the javascript variable
            document.write('inside if ');
            for (var i = 0; i < currentFriend.length; i++) {
                document.write(' Friend Name : "' + currentFriend[i] + '" <br />' + );
            }
        } else {
            document.write('inside else ');
        } %
        >
    </script>
</div>

I can see any output from the script tag ie. either 'inside if' nor 'inside else' is getting printed

I have even tried

<div id="tab2" class="tab">
     Page 2 am in friends page
     <%  if(currentFriend){ // currentFriend is the javascript variable

            for(var i=0;i<currentFriend.length;i++){ %>
             Friend Name : <%=currentFriend[i]%>           }
      <%} else { %>
              inside else
      <%}%>

</div>

But this is giving me an error which says currentFriend is not defined.

Please assist.

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Saurabh Jhunjhunwala
  • 2,832
  • 3
  • 29
  • 57
  • That's JavaScript code on top, EJS below. If it's saying it's not defined, maybe it's not defined? I don't see any AJAX here at all. – tadman Jul 14 '17 at 06:22
  • Possible duplicate of [Accessing EJS variable in Javascript logic](https://stackoverflow.com/questions/11289793/accessing-ejs-variable-in-javascript-logic) – Rajan Chauhan Jul 14 '17 at 06:22
  • @tadman, I have shared both possible options I tried. Did not share the Ajax call, because it is returning me the value, only issue I am facing now is how to use it – Saurabh Jhunjhunwala Jul 14 '17 at 08:53
  • @Rajan, The link in reference is going to refresh the page, whereas I am using an ajax call, because I don't want the page to reload. – Saurabh Jhunjhunwala Jul 14 '17 at 08:55
  • Where is the code that gets currentFriend? Perhaps it's a scoping issue. – Bobby Speirs Jul 14 '17 at 19:29

0 Answers0