Home > Enterprise >  unable to print the username onto console in JavaScript
unable to print the username onto console in JavaScript

Time:01-16

I have a html file with a linked js

<script type="text/javascript" src="{% static 'js/cart.js' %}">
  var user= '{{request.user}}'
</script>

and in cart.js i am trying to print the user variable but i keep getting an error saying uncaught ReferenceError user is not defined. any ideas on how to resolve this? this is cart.js

var updateBtns=document.getElementsByClassName("update-cart")
for(var i=0;i<updateBtns.length;i  ){
    updateBtns[i].addEventListener('click',function(){
        var pid=this.dataset.item
        var action=this.dataset.action
        console.log('pid:',pid,'action:',action)
    })
    console.log('USER',user)
    if(user=='AnonymousUser'){
        console.log('Not logged in')

    }else{
        console.log('User is logged in')
    }
}

CodePudding user response:

According to the w3 organization, if a <script> tag has a src="…" attribute, the content of the script is ignored, so it will never evaluate var user= …. You should work with two tags:

<script src="{% static 'js/cart.js' %}"/>
<script>
  var user = '{{request.user}}';
</script>

if js/cart.js needs to user the user variable, you need to define that first, so:

<script>
  var user = '{{request.user}}';
</script>
<script src="{% static 'js/cart.js' %}"/>

CodePudding user response:

I would recommend to add a breakpoint in your browser debugger in the line

var user=...

and reload the page. Thus you can see if the line is executed before the card.js script.

  • Related