This question already has an answer here:
I'm trying to create an image uploading website. In this, when a user logs in, I set a $_SESSION['id']
variable in php. Now, I wish to check if $_SESSION['id']
is set in my javascript file (general.js) in order to carry out certain functions. How should I go about doing it?
</div>
<?php $session_value=(isset($_SESSION['id']))?$_SESSION['id']:''; ?>
<html>
<head>
<script type="text/javascript">
var myvar='<?php echo $session_value;?>';
</script>
<script type="text/javascript" src="general.js"></script>
</head>
<body>
</body>
</html>
In above code snippet I have initialized global variable myvar with value stored into php session variable into script file before general.js file is referenced in script.It will be accessible in general.js file
A simple example please try this
<?php
session_start();
$_SESSION['id'] = 12;
?>
<script>
alert(<?php echo $_SESSION['id']; ?>);
</script>
You can even use php variable and array as variable in js like below
<?php
$id= $_SESSION['id'];
$data= array('one', 'two', 'three');
?>
<script type="text/javascript">
var idr = '<?php echo $id; ?>';
var datar = <?php echo json_encode($data); ?>;
</script>
The best way is to echo
the session ID in a javascript variable.
<script>
var sessionId = "<?php echo $_SESSION['id']; ?>";
// Your javascript code goes here
</script>
Here PHP is server-Side execution and JavaScript is Client side execution. and $_SESSION
is a server-side construct.So probably you can not access that directly using JavaScript You would need to store that variable in $_COOKIE
to be able to access it client-side.
You can get that Session using PHP, and then use that for the JavaScript like this
<?php
$variablephp = $_SESSION['category'];
?>
<script>
var variablejs = "<?php echo $variablephp; ?>" ;
alert("category = " + variablejs);
</script>
Here you are getting Session like echo $variablephp
using PHP, and the assign that value to JavaScript variable.