Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

211
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda