Use JS to take Hidden out of a div if PHP authorizes login

Asked

Viewed 42 times

-2

Good afternoon. I am making a simple login system and I am trying to make a div appear with the message "incorrect user and/or password(s)" if the login is refused. The login system is being done with PHP, and to take out Hidden JS usage. But I have no idea how to have a JS validation to achieve this. (Remembering that PHP is in a separate file and JS inside HTML).

HTML - the div I wish to take out the Hidden

<div class="div"><p>Usuário e/ou senha incorretos.</p>

PHP - login

$user = $_POST['user'];
$pw = $_POST['pw'];
$foi = true;

if(($user == "abc") && ($pw == "abc")){
    session_start();
    $_SESSION['login-session'] = $user;
    $_SESSION['senha-session'] = $pw;
    header('Location: restrito/index-restrita.php');

    
}else{
    header("Location: index.php");
    $foi = false;
   
}

JS - script

  <script language="javascript" type="text/javascript">
    function mostrarErro(){
        var log = <?=$foi?>
        if(log == false){
        document.getElementByClassName('div').style.display = 'block';
        }
    }


</script>

1 answer

1


UPDATE 06/07/2020

You cannot pass the variable $foi to another page even if it is also PHP

Create a $_SESSION['foi'] to pass values to another page

<?php
session_start();

$user = $_POST['user'];
$pw = $_POST['pw'];

if(($user == "abc") && ($pw == "abc")){
    
    $_SESSION['login-session'] = $user;
    $_SESSION['senha-session'] = $pw;
    $_SESSION['foi'] = "foi";
    header('Location: restrito/index-restrita.php');

    
}else{

    $_SESSION['foi'] = "nao foi";
    header("Location: index.php"); 

}
?>

Page with the div

<?php
session_start();
?>

<div class="div"><p>Usuario e/ou senha incorretos.</p></div>

<script language="javascript" type="text/javascript">
    function mostrarErro(){
        var log = "<?=$_SESSION['foi']?>";
        var elems = document.getElementsByClassName('div');
        var elem = elems[0];
        if(log == "nao foi"){
            elem.style.display = 'block';
        }else{
            elem.style.display = 'none';
        }
    }

</script>
  • As you can see in getElementsByClassName, Elements is plural and therefore returns a collection of all elements with this class, not a single element. You need to index the collection. You can access a certain element by the index. The index starts at 0. If you want the first (or only) element of the collection, use: elems[0].

OBS: session_start(); must be the first line of PHP

suporte navegador

Browser other questions tagged

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