I am trying to build some javascript function and I need to check if the users are logged in or not. When a user log in to my site I set a variable in session array named is_logged. I want to reach that variable in javascript is it possible??? I tried some ways but did not work like following:
var session = "<?php print_r $_SESSION['is_logged']; ?>";
alert(session);
and:
var session = '<?php echo json_encode($_SESSION['is_logged']) ?>';
alert(session);
It is either show a text or never alert at all
Your answer Hello @kartik, You can't set a server session variable directly from JS. //preliminary code Session::put('roleID', $request->input('role') );
Session is a variable on the backend server side, while JS is a previous script. There is no ready-made method in JS to get the value of Session, and it needs to be obtained through the server language. For example, java can be used to get the value of Session and assign it to JS variable.
To set session variables, you can use the global array variable called $_SESSION[]. The server can then access these global variables until it terminates the session. Now that you know what a session is in PHP and how to start one, it's time to look at an example and see how it works.
We need a session array to retain the data in different pages. Session arrays are like session variables which maintain a unique link between user's web page and the server.
Just echo it:
var session = <?php echo $_SESSION['is_logged']?'true':'false'; ?>;
alert(session);
You need tertiary operator, as false
is echoed as empty string so it would lead to var session = ;
which is a JS syntax error.
If you want to reach all elements of $_SESSION in JavaScript you may use json_encode,
<?php
session_start();
$_SESSION["x"]="y";
?>
<script>
var session = eval('(<?php echo json_encode($_SESSION)?>)');
console.log(session);
//you may access session variable "x" as follows
alert(session.x);
</script>
But note that, exporting all $_SESSION variable to client is not safe at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With