Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Weird Javascript behaviour, when combined with ejs Objects

I am currently working on a small account system and I would like to display the user data in an overview webpanel. The user object is passed through directly with the ejs file to the client after auth.
When accessing the user object directly through ejs statements everything works fine. It is also printable in Javascript after this line:

<script> 
const user = JSON.stringify(<%- JSON.stringify(user) %>);            
console.log(user); 
</script>

I can also print this object now in my js file. However I am not able to access certain variables of the object.
I have this function to display certain information on the panel:

function displayUserInfo() {
    console.log("User:" + user);
    console.log("Username:" + user.username);
    document.getElementById('profilePic').src = user.image;
    document.getElementById('usernameInput').value = user.username;
    document.getElementById('emailInput').value = user.email;
    document.getElementById('displaynameInput').value = user.displayname;
}

The output of this code in the console is as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

User:{"id":3,"username":"test@test","email":"test@test","image":null,"created_at":"1718643827967.0","salt":undefined,"password":undefined}
Username: undefined

Also all values I try to modify with this function are set to undefined.

I tried to wait for the site to finish loading and afterwards calling the function, but it didn’t help anything. I don’t understand why this is happening as I am able to access the same object on one line and one line later it seemingly disappears.

>Solution :

You’re converting the object to a string with the outer call to JSON.stringify(). Use:

const user = <%- JSON.stringify(user) %>;  

Note that you can’t concatenate strings and objects, so you should stringify when doing that.

console.log("User:" + JSON.stringify(user));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading