0
<?php if(isset($_SESSION['logged_in'])) {
    $somevar= "something";
?>

<script type="text/javascript">
    var somevar2 = <?php echo $value; ?>;
</script>

<?php } ?>

I put the code inside <head>, the console shows somevar2 is undefined, I was expecting the script don't run because it put in a scope where it execute only when user is logged in. What is the cause of this problem?

7
  • 3
    where is $value defined? Commented Dec 3, 2013 at 11:49
  • Most likely the error is coming from further down your code, where you try to access somevar2, but it doesn’t exist because the shown <script> block has not been written into the HTML output for the not logged-in user. Commented Dec 3, 2013 at 11:52
  • This is because $value is not declared anywhere in your code. Commented Dec 3, 2013 at 11:54
  • @WayneC in another file.php which when execute when the ajax query sent. Now I think it's because the ajax is slower than the script? Commented Dec 3, 2013 at 11:56
  • is value defined somewhere?. does $value contain something that will be evaluated as valid javascript? have you turned on all errors and warnings in php? Commented Dec 3, 2013 at 12:08

1 Answer 1

2
<?php if(isset($_SESSION['logged_in'])) {
    $somevar= "something";
?>

    <script type="text/javascript">
        var somevar2 = <?php echo $somevar; ?>;
    </script>

<?php } ?>

That should do the job. My guess is that you just forgot to change the variable echoed.

Sign up to request clarification or add additional context in comments.

3 Comments

That is Right. Danny. +1
This still isn't right, the result wouldn't be as expected. This would result in: var somevar2 = something; and something won't be defined in JS. This should be changed to: var somevar2 = <?php echo json_encode($somevar); ?>
no.. the somevar2 is defined at another file (process.php) where I used ajax.. what I want is, if the user is not logged in, don't run the script. possible?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.