Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?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 ?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading