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…
If you are using PHP 5.2.0 or later, change this:
To this:
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:
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.