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.

5
  • 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. Commented Jul 14, 2017 at 6:22
  • Possible duplicate of Accessing EJS variable in Javascript logic Commented Jul 14, 2017 at 6: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 Commented Jul 14, 2017 at 8: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. Commented Jul 14, 2017 at 8:55
  • Where is the code that gets currentFriend? Perhaps it's a scoping issue. Commented Jul 14, 2017 at 19:29

0

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.