Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 :

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda