Hello Im trying to pass value stored in php to javascript code.
I try to pass the value in $_SESSION[user]
If I have this script in my header:
<script>
var user = ? //How to pass the value?
</script>
In my buttons I do something like this:
onclick="foo('<?php session_start(); echo $_SESSION[user];?>')
But how do I pass it without the user click?
Thanks for helping
EDIT
My JS function located in other file and I reference them by this code in my header:
<script src="class_functions"></script>
How do I pass the same parameter to the other file?
-
possible duplicate of Passing a PHP variable to JavaScriptFloris– Floris2014年03月23日 14:05:40 +00:00Commented Mar 23, 2014 at 14:05
5 Answers 5
Just echo the PHP value out like you would any content:
<script>
var user = '<?php echo $_SESSION[user]; ?>';
</script>
JavaScript is just client-side code like HTML is.
6 Comments
If you're PHP script is rendering the page, I would go with the script tag approach.
<head>
<script type="text/javascript">
var user = '<?php echo $_SESSION["user"]; ?>';
</script>
</head>
<body>
</body>
Comments
Now that you have added an additional factor to your question, it is a little bit more interesting. If you need to set a variable when the functions that use this variable are located in a different file, then you need to decide the scope of the variable you are passing. There are several options; I will just list two:
Global scope. That is, the variable will be "known" to the other functions because of where it it located. You want to be careful of this, but if that's your approach you can use any of the answers given, e.g.
<script> var x = '<?= $_SESSION["user"];>'; </script>Local scope. Now you will need to include a function in
class_functionsthat sets the variable. You might end up with something like<script> set_user('<?= $_SESSION["user"];>'); </script>
Where the set_user() function is defined in your other file, and ensures that the variable is available to the other functions with the correct scope.
I would prefer using method 2 - it is much cleaner.
1 Comment
I think this is better:
<script>
var user = '<?php echo htmlentities($_SESSION["user"]); ?>';
</script>
Because if there are quotes $_SESSION['user'], you will get an error. For example if you have:
$_SESSION['user'] = "something with 'quotes'";
the js would like so:
var user = 'something with 'quotes'';
Which is incorrect.
2 Comments
You Can use Jquery ,if you want it to happen automatically.
just Use the following code inside your tags
$(document).ready(function()
{
var user= <? echo $_SESSION['user']?>;
//Code Goes here......
});
Hope that solves Your Problem
Note:This can be one of the many possible solutions