I have in session PHP:
$_SESSION['id'] = 2;
how can i get this for jQuery?
<script>
var sessionid = ??? ;
alert(sessionid);
</script>
I have in session PHP:
$_SESSION['id'] = 2;
how can i get this for jQuery?
<script>
var sessionid = ??? ;
alert(sessionid);
</script>
Share
Improve this question
asked Jan 9, 2012 at 11:53
Mark FondyMark Fondy
3,9338 gold badges26 silver badges26 bronze badges
4 Answers
Reset to default 5<script>
var sessionid = "<?php echo $_SESSION['id'] ?>" ;
alert(sessionid);
</script>
don't forget to call session_start();
You could set it as the ID of an element (like the HTML element) if you want to access it from a script:
<html id="<?php echo $_SESSION['id']; ?>">
In the external script:
var sessionid = $('html').attr('id');
alert (sessionid);
This has the added benefit of being able to be read by an external script.
EDIT:
You would need to set the session before you output anything, so the full code would be something like:
<?php
session_start();
if (!isset($_SESSION['id']))
$_SESSION['id'] = 'session1';
?><html id="<?php echo $_SESSION['id']?>">
<head>
<title>SESSION ID TEST</title>
<script>
$(function(){
var sessionid = $('html').attr('id');
alert (sessionid);
})
</script>
</head>
</html>
javascript executes on the client, which has no knowledge of a session id natively. You'll have to echo out the session id to assign the value to a javascript variable:
var sessionid = "<? echo $_SESSION['id']?>";
How about..
<script>
var sessionid = "<? echo $_SESSION['id']?>";
alert(sessionid);
</script>