Shimon
Shimon

Reputation: 13

js function containing php executes when not called

I have the following code within the tag of my page:

<script>
    function LogInOut()
    {
        // Get the current login status
        alert("executing LogInOut");
        $loginStatus = "<?php echo $_SESSION['login']; ?>";
        if ($loginStatus == "true")
        {
            <?php
                echo "<br />script function";
                $_SESSION['login'] = "false";
                session_destroy();
            ?>
            document.getElementById("loginState").innerHTML = "login";
        }
        else
        {
            window.location = 'login.php';
        }
    }

</script>

I find that the php code executes when the page loads. The function (for debugging) is NEVER called yet the php code executes while none of the rest of the script executes! Can anyone clarify why this could be happening?

thank you, Shimon

Upvotes: 0

Views: 108

Answers (2)

Yap Kai Lun Leon
Yap Kai Lun Leon

Reputation: 326

You will need something to call the function In your case, call it when page is ready.

$(document).ready(function(){
     LogInOut();
});

Or using a console for modern browser type in:

LogInOut();

Upvotes: 0

Jay Harris
Jay Harris

Reputation: 4271

Classic case of mixing Javascript, a client side language, with PHP, a server side language. They run at two different locations and that being said this will never be possible.

PHP runs before javascript and if your trying to mix it with javascript, use it to echo dynamic data. eg:

var logged_in = <?=($_SESSION['login'] ? 'true' : 'false')?> ;

Javascript runs within the browser and after PHP, do not use php code thinking it will run inside of the browser

Upvotes: 1

Related Questions