Passing PHP variable into JavaScript [duplicate]

In your PHP file you could set your user as a global varibale:

<script type="text/javascript">
    var ptamzzNamespace = {
       sessionUser : '<?php echo $_SESSION['user']; ?>'
    }        
</script>

Include this before including your external JavaScript code.

Then in your JavaScript file you can use it:

$.("#btn').click (
     function() {
        alert(ptamzzNamespace.sessionUser);
     }
)

Additionally:
If you’re not sure if your session varibale can contain quotes itsself, you can use addslashes() to fix this problem:

<?php echo addslashes($_SESSION['user']); ?> even if this will maybe produce something you don’t really want to display (because it produces a string with slashes) it will help that your code will not fail. (Thanks to Artefacto)

Would this be an option for you?

Leave a Comment