Sarah
Sarah

Reputation: 1905

How to save user session in a variable in PHP to be referenced in JavaScript

Case: User clicks on an image

I am now showing the pop-up div whenever the image is being clicked. Any advice on how to save the session and refer it as the variable in a JavaScript to perform a function like:

if {
    // user is log in.. do your task here..
} else {
    //user is not log in.. do your task here...
}

EDIT:

<script>
<? if(isset($_SESSION["logged_in"])) {
    echo "var $check=1";
} else {
    echo "var $check=0";
} ?>

function SetMood() {
    if($check==1) {
        // user is log in.. do your task here..
        alert('URL');
    } else {
        //user is not log in.. do your task here...
        document.getElementById('light').style.display='block';
        document.getElementById('fade').style.display='block';
        document.getElementById('fade').scrollIntoView(true);
    }
}
</script>

This is called for the image as:

<a id="register" href = "javascript:void(0)" onclick = "SetMood();" data-fancybox-group="gallery">
    <img src="<cms:show my_image_thumb />" alt="" class="fade">
</a>

The above has no effect and now nothing opens onClick

Upvotes: 0

Views: 519

Answers (2)

David
David

Reputation: 218827

Don't perform the conditional check in client-side code, perform it in server-side code.

Assuming you have JavaScript implementations of what you want to achieve, let's call them these respectively:

navigateToLink();
showPopUp();

Then you'd conditionally emit the code for one or the other depending on a server-side session check. Something like this:

<?php
if ($_SESSION['someValue'] == 'someKnownValue') {
?>
    navigateToLink();
<?php
} else {
?>
    showPopUp();
<?php
}
?>

The idea is that server-side code should determine what the user can or can not do. Anything emitted to client-side code is entirely visible to (and modifiable by) the user.

Upvotes: 2

Pinki
Pinki

Reputation: 1042

This should help you:

<script>
    var yourValue = '<?php echo $_SESSION['yourSessionValue'] ?>';
    if(yourValue == 'hello') {
        console.log('hide yo kids');
    } else {
        console.log('hide yo wife');
    }
</script>

Upvotes: 0

Related Questions