Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  59] [ 6]  / answers: 1 / hits: 24017  / 14 Years ago, tue, march 15, 2011, 12:00:00

I've a PHP session variable, $_SESSION['user'], alive throughout the session. In the head section, I've my JavaScript file included, scripts.js.



How do I pass the session variable into the JavaScript file if I want something like the following.



$.(#btn').click (
function() {
alert('<?php echo $_SESSION['user']; ?>');
}
)


As the <?php ?> isn't recognized in the JavaScript file, the code above doesn't work. So I've to put in the PHP file itself, but how do I keep it in the JavaScript file?


More From » php

 Answers
8

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?


[#93282] Sunday, March 13, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
estefanib

Total Points: 508
Total Questions: 104
Total Answers: 83

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
;