Skip to content
Advertisement

How to put a MySQL table column as a variable in ?

I recently made a PHP, HTML, jQuery chat system and I want the users to have the same name in chat, as their login. The whole webpage is already connected to the MySQL database. I want to focus on how to put a $_SESSION(login_user); as a variable in the jQuery script. Can somebody help me out?

    var name = [display username];

Advertisement

Answer

Javascript itself can’t access the session data. Hence you don’t have access to the username directly.

There’s a few ways you can get the username. One is like Way to Developer described and just shove php code inside a script tag.

However since this is not really sensible data I would add that info to your body as a data attribute and then access it with javascript directly.

<body data-username="<?php echo (isset($_SESSION['username'])) ? $_SESSION['username'] : null; ?> "

Then in your javascript you can just do (since you tagged jquery I assume you’re using it):

var username = $('body).data('username');
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement