Home > Mobile >  Is the function binded to the button always executed or did I make a mistake?
Is the function binded to the button always executed or did I make a mistake?

Time:05-08

So I have this PHP page, with at the start some unimportant stuff and a session opening :

<?php
    session_start();
?>

I want the disconnect button to appear only if the user is already connected, which means that $_SESSION['Pseudo'] is set. If this is the case, I create a button, and bind to that button a function to destroy the session. The problem is, each time I go on this page, the session is destroy, even though it's in a condition.

Here's my code :

<?php
if (isset($_SESSION["pseudo"])) {
    echo '<p><button type="button" id="deco">Disconnect</button></p>';
}
?>
<script>
    let btn = document.getElementById('deco');
    if (btn) {
        btn.addEventListener('click', updateBtn);
        function updateBtn() {
            <?php
            session_destroy();
            ?>
            window.location.href = "/"
        }
    }
</script>

Any clue ?

CodePudding user response:

You cannot combine PHP within Javascript like that.

When you're doing , it's not a part of the Javascript. It's PHP code and is executed as part of the PHP code in the file.

This means that it has nothing to do with the javascript aspect. your updateBtn function is effectively, when the page source code loads:

function updateBtn() { window.location.href = "/" }

What you really want to do is make it so that when someone clicks the button, it takes them to a logout page or a page with a logout query param.

eg.

<?php


if (isset($_GET['action']) && $_GET['action'] === 'logout') {
  session_destroy();
  echo 'You have successfully logged out!';
}
if (isset($_SESSION["pseudo"])) {
    echo '<p><button type="button" id="deco">Disconnect</button></p>';
}
?>

<script>
    let btn = document.getElementById('deco');
    if (btn) {
        btn.addEventListener('click', updateBtn);
        function updateBtn() {
            window.location.href = "/?action=logout"
        }
    }
</script>
  • Related