Read JS file before PHP

Asked

Viewed 139 times

-2

Just a question, I made an HTML sign-up screen, and created a Javascript file where checks the amount of password and if the passwords are equal. And I made a file receives.php, where will send the registration information to the local bank (because I am testing). Now comes my question, if I put different password, it shows me an alert, saying that the password are different, but when I click on ok, it saves the information in the bank, was not to do this, was to go back to the screen, for user to put again the password, the same happens when the password has less than 6 digits.

JS file

function Salvar(){

    senha1 = document.f1.senha1.value;
    senha2 = document.f1.senha2.value;

    if (senha1 == senha2){
            document.getElementById("senha1").style.borderColor="#bfc4c6";
            document.getElementById("senha2").style.borderColor="#bfc4c6";
        }

    else{
            document.getElementById("senha1").style.borderColor="#f00"; //caso for diferente irá mudar a cor do campo
            document.getElementById("senha2").style.borderColor="#f00";
            alert("SENHAS DIFERENTES");
             window.location="cadastro.html";
        }
}

Php file:

<?php

    include_once 'conexao.php';

    $nome=$_POST['nome'];
    $cpf=$_POST['cpf'];
    $telefone=$_POST['telefone'];
    $email=$_POST['email'];
     $usuario=$_POST['usuario'];
    //$senha1=$_POST['senha1'];
    $senha1 = md5($_POST['senha1']);

    $sql1 = $dbcon->query("SELECT * FROM clientes WHERE Email='$email' or usuario='$usuario'");

    if(

    if(mysqli_num_rows($sql1) > 0){
        echo "Este usuario ja existe!";
        echo "<script>window.location='index.html';alert('Este usuario/email ja existe');</script>"; //irá redirecionar para página de login
    } else {
        $sql2 = $dbcon->query("INSERT INTO clientes (usuario,nome,cpf,telefone,email,senha1) VALUES('$usuario','$nome','$cpf','$telefone','$email','$senha1')");

    if($sql2){
            //echo  "<meta http-equiv='Refresh' content=0;URL=index.html>";
            echo "<script>window.location='index.html';alert('$nome, cadastro realizado com sucesso');</script>"; //irá redirecionar para página de login
    }else{
            echo "registro_erro";
        }
    }
    if(!mpty($_POST['nome'])){
        echo "<script>window.location='cadastro.html';alert('Campos obrigatorios');</script>";

    }
?>

HTML code

<div class="input-div" id="input-senha1"><b>Senha:</b>
     <input type="password" required id="senha1" name="senha1" placeholder="Insira senha " onkeyup="javascript:verifica()">
     <table id="mostra"></table>
</div>
<div class="input-div" id="input-senha2"><b>Confirmar senha:</b>
     <input type="password" required id="senha2" name="senha2" placeholder="Digite novamente a senha ">
</div>
<div class="content">
    <input type="submit" class="botao01"  onclick="Salvar();" value="Salvar" />
</div>

I couldn’t put the code with the html tags

  • In addition to checking by Javascript you should also check in PHP and prevent the code that saves in the database from running. But it would be better if the form was not sent if the passwords do not trust. But what did not give to understand right is the use of the function Salvar(). How you are calling it and what is the function of this redirection window.location="cadastro.html";?

  • You can perform the validation of passwords via Blur in the fields, I believe it is better in your case.

  • I put the html code, but I couldn’t put it with the tags.

  • In case you would have to put this way to redirect back to login screen: window.location.pathname="cadastro.html", and also, prevent sending the form in case of incorrect password.

  • But how would I do that, Matheus Spoo? because I tried this way putting in the javascript file and then in php, but it did not work, it goes back to the screen, but saves the data. But it was to prevent this. I realized that the php file is read before javascript

  • Before redirecting you must stop the default click behavior, which in case is a submit the form. https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

  • Paul, I put evt.preventDefault(), but it keeps saving when the password is less than 6 digits :(

Show 2 more comments

1 answer

0

The Event.preventDevault() works perfectly.

I recommend that in addition to validating on the front end, also validate on the back end.

For educational purposes only, below is an implementation very close to your example. Note that in this case I put everything in a single page . php.

I tested it here and it worked perfectly.

I hope it helps.

<?php
/*
CREATE TABLE `teste`.`clientes`(  
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `nome` VARCHAR(150) NOT NULL,
  `email` VARCHAR(150) NOT NULL,
  `usuario` VARCHAR(30) NOT NULL,
  `senha` VARCHAR(255) NOT NULL,
  `cpf` VARCHAR(14) NOT NULL,
  `telefone` VARCHAR(15) NOT NULL,
  `ativo` TINYINT(1) NOT NULL DEFAULT 1,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `clientes_email_unique` (`email`),
  UNIQUE INDEX `clientes_usuario_unique` (`usuario`),
  INDEX `clientes_ativo_email_index` (`email`, `ativo`),
  INDEX `clientes_ativo_usuario_index` (`usuario`, `ativo`)
);
*/
function conecta(){
    $mysqli = new mysqli('localhost', 'usuario-do-banco', 'senha', 'nome-do-banco');
    if ($mysqli->connect_errno) {
        throw new Exception(sprintf('Não foi possível contectar ao banco de dados. Motivo:', $mysqli->connect_error));
    }
    return $mysqli;
}

function normalizaDados(array $post){
    $nome       = !empty($post['nome']) ? trim($post['nome']) : null;
    $email      = !empty($post['email']) ? trim($post['email']) : null;
    $usuario    = !empty($post['usuario']) ? trim($post['usuario']) : null;
    $cpf        = !empty($post['cpf']) ? trim($post['cpf']) : null;
    $telefone   = !empty($post['telefone']) ? trim($post['telefone']) : null;
    $senha      = !empty($post['senha']) ? trim($post['senha']) : null;
    $confirmar  = !empty($post['confirmar-senha']) ? trim($post['confirmar-senha']) : null;

    return [
        'nome'      => $nome,
        'email'     => $email,
        'usuario'   => $usuario,
        'cpf'       => $cpf,
        'telefone'  => $telefone,
        'senha'     => $senha,
        'confirmar' => $confirmar,
    ];
}

function validaCamposObrigatorios(array $dados){
    //todos os campos sao obrigatorios
    foreach ($dados as $key => $value) {
        if (empty($value)) {
            throw new Exception(sprintf('O campo "%s" é obrigatório.', $key));
        }
    }
}

function validaSenha($senha, $confirmar){
    if (strlen($senha) < 6) {
        throw new Exception('A senha deve ter ao menos 6 caracteres.');
    }
    if ($senha !== $confirmar) {
        throw new Exception('As senhas não conferem.');
    }
}

function validaEmail($dbcon, $email){
    $stmt = $dbcon->prepare('SELECT `id` FROM `clientes` WHERE `email` = ? LIMIT 1;');
    if (!$stmt) {
        throw new Exception('Erro ao preparar a consulta de validação de e-mail.');
    }
    $stmt->bind_param('s', $email);
    if (!$stmt->execute()) {
        $stmt->close();
        throw new Exception('Erro ao executar a consulta de validação de e-mail.');
    }
    $stmt->bind_result($id);
    $stmt->fetch();
    $stmt->close();
    if ($id) {
        throw new Exception('E-mail já utilizado.');
    }
}

function validaUsuario($dbcon, $email){
    $stmt = $dbcon->prepare('SELECT `id` FROM `clientes` WHERE `usuario` = ? LIMIT 1;');
    if (!$stmt) {
        throw new Exception('Erro ao preparar a consulta de validação de usuário.');
    }
    $stmt->bind_param('s', $email);
    if (!$stmt->execute()) {
        $stmt->close();
        throw new Exception('Erro ao executar a consulta de validação de usuário.');
    }
    $stmt->bind_result($id);
    $stmt->fetch();
    $stmt->close();
    if ($id) {
        throw new Exception('Usuário já utilizado.');
    }
}

function validaDados($dbcon, array $dados){
    validaCamposObrigatorios($dados);
    validaSenha($dados['senha'], $dados['confirmar']);
    validaEmail($dbcon, $dados['email']);
    validaUsuario($dbcon, $dados['usuario']);
}

function insereDados($dbcon, array $dados){
    $stmt = $dbcon->prepare('INSERT INTO `clientes`(`nome`, `email`, `usuario`, `cpf`, `telefone`, `senha`, `ativo`) VALUES(?, ?, ?, ?, ?, ?, 1);');
    if (!$stmt) {
        throw new Exception('Erro ao preparar a consulta de criação do cliente.');
    }
    $stmt->bind_param(
        'ssssss', 
        $dados['nome'], 
        $dados['email'], 
        $dados['usuario'], 
        $dados['cpf'], 
        $dados['telefone'], 
        md5($dados['senha']) 
    );
    if (!$stmt->execute()) {
        $error = $stmt->error;
        $stmt->close();
        throw new Exception('Erro ao executar a consulta de criação de cliente: ' . $error);
    }
    $stmt->close();
    return $dbcon->insert_id;
}

$mensagem = '';

$dados = normalizaDados($_POST);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    try{
        $dbcon = conecta();

        validaDados($dbcon, $dados);

        insereDados($dbcon, $dados);

        //para redirecionar para o login.php
        //tirar o comentário das linhas abaixo.
        //header('Location: /login.php');
        //exit;

        $mensagem = 'Usuário inserido com sucesso.';

        $dados = normalizaDados([]);
    } catch (Exception $e) {
        $mensagem = $e->getMessage();
    }
}
?><!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="utf-8">
        <title>Cadastro</title>
    </head>
    <body>
        <form method="POST" id="formulario" onsubmit="validaFormulario(event)">
            <div id="mensagem"><?php echo $mensagem; ?></div>

            <div>
                <label for="nome">Nome: *</label>
                <input type="text" required minlength="6" id="nome" name="nome" placeholder="Nome" value="<?php echo $dados['nome']; ?>">
            </div>

            <div>
                <label for="email">E-mail: *</label>
                <input type="email" required id="email" name="email" placeholder="E-mail" value="<?php echo $dados['email']; ?>">
            </div>

            <div>
                <label for="usuario">Usuário: *</label>
                <input type="text" required minlength="4" id="usuario" name="usuario" placeholder="Usuário" value="<?php echo $dados['usuario']; ?>">
            </div>

            <div>
                <label for="senha">Senha: *</label>
                <input type="password" required minlength="6" id="senha" name="senha" placeholder="Insira senha" onkeyup="comparaSenhas()">
            </div>

            <div>
                <label for="confirmar-senha">Confirmar senha: *</label>
                <input type="password" required minlength="6" id="confirmar-senha" name="confirmar-senha" placeholder="Confirme a senha " onkeyup="comparaSenhas()">
            </div>

            <div>
                <label for="cpf">CPF: *</label>
                <input type="text" required id="cpf" name="cpf" placeholder="CPF" value="<?php echo $dados['cpf']; ?>">
            </div>

            <div>
                <label for="telefone">Telefone: *</label>
                <input type="text" required id="telefone" name="telefone" placeholder="Telefone" value="<?php echo $dados['telefone']; ?>">
            </div>

            <div>
                <input type="submit" value="Salvar">
            </div>
        </form>

        <script>
            var $senha = document.getElementById('senha');
            var $confirmarSenha = document.getElementById('confirmar-senha');
            var $mensagem = document.getElementById('mensagem');

            function comparaSenhas(){
                if ($senha.value && $confirmarSenha.value && $senha.value == $confirmarSenha.value) {
                    $mensagem.innerText = '';
                    return true;
                } 
                if ($senha.value && $confirmarSenha.value) {
                    $mensagem.innerText = 'As senhas não conferem.';
                }
                return false;
            }

            function validaFormulario(event) {
                console.log('validando o formulário...');
                if (!comparaSenhas()) {
                    console.log('formulário inválido! submit impedido.');
                    event.preventDefault();
                }
                console.log('formulário valido!');
            }
        </script>
    </body>
</html>

Browser other questions tagged

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