Javascript call within PHP

Asked

Viewed 616 times

0

Good afternoon, I’m having trouble running a Javascript code inside PHP. My intention is for the user to err the login and password appear a message on the Login screen warning the same that it erred, using Javascript making it remove a class called "class-invisible".

Follow the code below:

if ($resultado > 0) {
        logaUsuario($usuario->id, $usuario->nome, $usuario->grupo);
        header("Location: index.php");
    } else {
        echo "<script language='javascript' type='text/javascript'>
                function mostrarErro() {
                var alerta = $('.alerta-erro');

                alerta.removeClass('classe-invisivel');
                setTimeout(function() {
                alerta.addClass('classe-invisivel');
                }, 6000);
            }
                mostrarErro();
                window.location.replace('login.php');
              </script>";
    }

I can’t see where I’m going wrong. Someone could guide me, some hint?

Thank you!

1 answer

-1


Making the call that way is bad practice. Put the function in a JS file and escape to the login page in the onload event of the body tag the call of the function show().

<?php

// Suas regras de login
$erroLogin = false;

if ($resultado > 0) {
    //Se houver sucesso
    logaUsuario($usuario->id, $usuario->nome, $usuario->grupo);
    header("Location: index.php");

} else {
    //Se falhar
    $erroLogin = true;        
}


[....]
<html>
    <head>
    <script language='javascript' type='text/javascript'>
            function mostrarErro()
            {
                var alerta = $('.alerta-erro');
                alerta.removeClass('classe-invisivel');

                setTimeout(function() {
                    alerta.addClass('classe-invisivel');
                }, 6000);
            }
              </script>
    </head>
    <body <?php echo (isset($erroLogin) && $erroLogin === true) ? 'onload="javascript:mostrarErro();"' : null ;?>>

    [...]

    </body>
</html>
  • Thank you for the guidance that this is not good practice and for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.