Is it possible to read a session value with Javascript?
For example, if I assigned a value into a session in PHP:
$_SESSION['msg'] = "ABC Message";
Is it possible to read $_SESSION['msg']
with Javascript?
Is it possible to read a session value with Javascript?
For example, if I assigned a value into a session in PHP:
$_SESSION['msg'] = "ABC Message";
Is it possible to read $_SESSION['msg']
with Javascript?
A very simple way is to generate the JavaScript with some PHP code:
<script type="text/javascript">
<?php echo 'var msg = "'.json_encode($_SESSION['msg']).'";';
</script>
$_SESSION is a server-side construct. You would need to store that variable in $_COOKIE to be able to access it client-side.
.. Or you can use ajax to retrive your server side session value into you client-side javascript.` (quick, dirty and untested example, using jQuery)
Javascript Side:
$.ajax({
url: "test.php",
cache: false,
success: function(html){
eval( html ); /// UGLY NASTY YOU MUST VALIDATE YOUR INPUTS... JUST AN EXAMPLE
}
});
PHP side test.php:
echo 'var myData = "'. $_SESSION['msg'].'"';
If this helps anyone, those examples returned null
, so I just used:
<?php session_start();
$msg = $_SESSION['msg'];
?>
<script>
<?php echo "var msg = '" .$msg . "'"; ?>
</script>
To make an even easier example of Luis Melgratti´s answer you can just return a json encoded value from PHP and use jQuery to parse it, like this:
Javascript:
$("#some_button")
.click(function()
{
$.ajax(
{
url: "get_session.php",
cache: false
})
.done(function(result)
{
var session_credentials = $.parseJSON(result);
console.log(session_credentials);
});
});
PHP:
//get_session.php
<?php
session_start();
echo json_encode($_SESSION);
?>
I believe there are even more answers on a similar SO-thread here: how-to-access-php-session-variables-from-jquery-function-in-a-js-file
May It Works :
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
getCookie('PHPSESSID');
<script type="text/javascript">
var foo="<?php echo $_SESSION['user_id']; ?>";
alert(foo);
</script>