Basel
Basel

Reputation: 1365

How to reach php $_SESSION array in javascript?

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

Upvotes: 6

Views: 15062

Answers (6)

Nesmar Patubo
Nesmar Patubo

Reputation: 74

You can do things like this

Just insert the $_SESSION['is_logged'] in a hidden field like

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

Then you can access that in your jquery like this

var is_logged = jQuery.trim($('#is_logged').val());
//then do validation here

Upvotes: 0

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

In a js file you cant get the value of a php variable or php code doesnt works on a js file because php code will works in a .php extension file. So one method is to set the session value as a hidden element value and in your js file get the value of the hidden element.

In the html:

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

In your js:

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

Upvotes: 0

Kemal Dağ
Kemal Dağ

Reputation: 2763

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.

Upvotes: 2

Aas Mohammd
Aas Mohammd

Reputation: 70

   var get_session=<?php echo $_SESSION['is_login'] 

  alert(get_session);
    ?>

## *Just try this * ##

Upvotes: -5

Martin Lantzsch
Martin Lantzsch

Reputation: 1901

Try the following code:

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

Upvotes: 0

Voitcus
Voitcus

Reputation: 4446

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.

Upvotes: 6

Related Questions