Anon
Anon

Reputation: 1221

Session var not accessible in my script

I have two $_SESSION variables impossible to access in any script of my page but it's sure they exist in the PHP code of the same page when I use echo to display their values.

I can display in jQuery every classical PHP variables I want with the following code, but it's impossible when they are $_SESSION variables :

<?php if( isset($_SESSION['id']) ){ 
    echo $_SESSION['id'];   // it displays the value
} ?>

<script type="text/javascript">
$(document).ready(function() {  

$("#some_button").click(function(){
    var a = <?php echo $_SESSION['id']; ?>; 
    alert(a);
});         
}); 
</script>

I don't understand why honestly...

Upvotes: 0

Views: 222

Answers (4)

adeneo
adeneo

Reputation: 318372

If its a string:

var a= "<?php echo $_SESSION['id']; ?>";

Upvotes: 1

devasia2112
devasia2112

Reputation: 6044

It is working to me: Ready and test the code below, it is quite similar to your code, but I think you forgot to call jquery api.

<?php>
session_start();
$_SESSION['id'] = 1;

if ( isset($_SESSION['id']) )
{ 
    echo $_SESSION['id'];
    echo json_encode($_SESSION['id']);
}
?>

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() 
{
    $("#some_button").click(function(){
            var a = "Result: "+ <?php echo json_encode($_SESSION['id']); ?>;
        //var a="<?php echo $_SESSION['id']; ?>";
            alert(a);
    });      
});
</script>

<form method="post" name="form" action="#">
    <input type="submit" id="some_button" value="Clique" />
</form>

Upvotes: 1

Trott
Trott

Reputation: 70183

If you are using PHP 5.2.0 or later, change this:

var a = <?php echo $_SESSION['id']; ?>; 

To this:

var a = <?php echo json_encode($_SESSION['id']); ?>

That will put quotation marks around the result if necessary and escape characters for JavaScript as needed.

If you want to use something earlier than PHP 5.2.0, you can do something like this:

var a = '<?php echo $_SESSION['id']; ?>'

Ideally, though, you'd want to use a regexp and/or escaping/replacing functions unless you know that $_SESSION['id'] will only have safe characters. json_encode() has that stuff baked in already, so it's preferable.

Upvotes: 3

dotoree
dotoree

Reputation: 2993

I don't know if the example is in the same page but i suspect you 're missing session_start() so you can't use session variables

Upvotes: 2

Related Questions