How to get to php $ _SESSION array in javascript?

I am trying to create some javascript function and I need to check if users are logged in or not. When a user logs in to my site, I set a variable in the session array called is_logged. I want to achieve this variable in javascript, is this possible ??? I tried several ways, but did not work as shown below:

var session = "<?php print_r $_SESSION['is_logged']; ?>"; alert(session); 

and

 var session = '<?php echo json_encode($_SESSION['is_logged']) ?>'; alert(session); 

It either shows the text or never warns at all

+4
source share
6 answers

If you want to cover all the elements of $ _SESSION in JavaScript, you can 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 keep in mind that exporting the entire $ _SESSION variable to the client is not safe at all.

+2
source

Just an echo:

 var session = <?php echo $_SESSION['is_logged']?'true':'false'; ?>; alert(session); 

You need a tertiary operator, since false reflected as an empty string, so this will result in var session = ; , which is a JS syntax error.

+6
source

In the js file, you cannot get the value of the php variable or php code that does not work in the js file, because the php code will work in the .php extension file. Thus, one of the methods is to set the session value as the value of the hidden element, and in your js file to get the value of the hidden element.

In html:

 <input type="hidden" id="sess_var" value="<?php echo $_SESSION['is_logged']; ?>"/> 

In js:

 var session = document.getElementById('sess_var').value; alert(session); 
0
source

Try using the following code:

 var session = "<?php echo $_SESSION['is_logged'] ?>"; 
0
source

You can do such things

Just paste $_SESSION['is_logged'] into the hidden field, for example

 <input type = "hidden" value = "<?php echo $_SESSION['is_logged']; ?>" id = "is_logged" /> 

Then you can access this in your jquery like this

 var is_logged = jQuery.trim($('#is_logged').val()); //then do validation here 
0
source
  var get_session=<?php echo $_SESSION['is_login'] alert(get_session); ?> 

## * Just try this * ##

-4
source

Source: https://habr.com/ru/post/1487836/


All Articles