Ajax receiving array that shouldn’t

Asked

Viewed 50 times

0

I’m putting together a popup registration form, so I had to use Ajax for authentication. It happens that when I type an already registered email it shows me the message correctly (already registered email! ), but when I put an unregistered email, it first shows me the message from (already registered email! ) and then shows me the message (Successfully registered!).

$("#btn-cadastro").click(function(){

var data = $("#myRegister").serialize();

$.ajax({
type : 'POST',
url  : 'conexao/cadastro.php',
data : data,
dataType: 'json',
beforeSend: function()
{   
    $("#btn-cadastro").html('Validando ...');
},
success :  function(response){                      
    if(response.erro == "0"){   
        $("#pass-info3").css('display', 'none')
        $("#btn-cadastro").html('Entrar');
        $("#btn-cadastro").prop('disabled', true);
        setTimeout(function () {
        $("#pass-info3").removeClass( "weakpass" )
        $("#pass-info3").addClass( "goodpass" )
        $("#pass-info3").css('display', 'block')
        $("#pass-info3").html(response.mensagem);
        }, 4101);
        setTimeout(function () {
        window.location.href = "index.php";
        }, 6101);
    }else{
        if(response.erro == "1"){   
            $("#pass-info3").css('display', 'none')
            $("#pass-info3").removeClass( "goodpass" )
            $("#pass-info3").addClass( "weakpass" )
            $("#btn-cadastro").prop('disabled', true);
            setTimeout(function () {
            $("#btn-cadastro").html('Entrar');
            $("#btn-cadastro").prop('disabled', false);
            $("#pass-info3").css('display', 'block')
            $("#pass-info3").html('<strong>Erro! </strong>' + response.mensagem);
            }, 500);
        }
    }
}
});
});

And the php that makes the registration is this:

// Conexao com o Banco de Dados
require_once("conexao.php");

// Recebe os dados de cadastro
$nome       = (isset($_POST['nome'])) ? $_POST['nome'] : null;
$email      = (isset($_POST['email'])) ? $_POST['email'] : null;
$telefone   = (isset($_POST['telefone'])) ? $_POST['telefone'] : null;
$senha      = (isset($_POST['senha'])) ? $_POST['senha'] : null;
$rsenha     = (isset($_POST['rsenha'])) ? $_POST['rsenha'] : null;

// Criptografa senha
$custo     = '08';
$salt      = 'Cf1f11ePArKlBJomM0F6aJ';
$hash = crypt($senha, '$2a$' . $custo . '$' . $salt . '$');

if (empty($nome) || empty($email) || empty($telefone) || empty($senha) || empty($rsenha)):
    $retorno  = array('erro' => '1', 'mensagem' => 'Preencha todos os campos!');
    echo json_encode($retorno);
else:

    $sql = 'SELECT * FROM usuarios WHERE email = :email';
    $stmt = $conexao->prepare($sql);
    $stmt->bindParam(':email', $email);
    $stmt->execute();

    $resposta1 = $stmt->fetch(PDO::FETCH_ASSOC);

    if (is_array($resposta1)):
        $retorno  = array('erro' => '1', 'mensagem' => 'E-mail ja registrado!');
        echo json_encode($retorno);
    else:
        $sql2 = 'INSERT INTO usuarios(nome, email, telefone, senha) VALUES(:nome, :email, :telefone, :hash)';
        $stmt2 = $conexao->prepare($sql2);
        $stmt2->bindParam(':nome', $nome);
        $stmt2->bindParam(':email', $email);
        $stmt2->bindParam(':telefone', $telefone);
        $stmt2->bindParam(':hash', $hash);
        $resposta2 = $stmt2->execute();

        if( ! $resposta2 ):
            $retorno  = array('erro' => '1', 'mensagem' => 'Não foi possivel completar o cadastro!');
            echo json_encode($retorno);
        else:
            $retorno  = array('erro' => '0', 'mensagem' => 'Cadastrado com sucesso!');
            echo json_encode($retorno);
        endif;
    endif;
endif;

I have another one just like that with only 1 query for Login, and it works normally. I imagine it must be something that went unnoticed or that I don’t really know, so I’d appreciate it if you could help me!

1 answer

0

Probably the $stmt->fetch(PDO::FETCH_ASSOC); returns an empty array when the record does not exist.

Try changing the following line:

if (is_array($resposta1)):

To

if (is_array($resposta1) && count($resposta1) > 0):
  • Friend, it gave the same thing. I did a test here now of this query without PDO, in the old way with (mysqli_num_rows($sql)>0), it does the same thing. And another thing, it has if: Else: endif; if it appears that the email is already registered, it is because it stopped in the correct If ? Why then would he be going on to Isis, he’s doing everything, both if and Isis.

  • You’re right, so from what you described, you seem to be calling the page twice. Try adding a check to validate whether a post has occurred on the page. if (!empty($_POST)). I’m not sure Empty will work for null fields. So you may be passing the Empty validation if you’re falling into the ES of your ternary condition.

  • Friend, apparently the problem was not in PHP, but in JS, as you can see, I put the Ajax request inside my validation, so that if everything was correct, it would execute the Ajax request. I made a test I put that if everything was right, a variable errorsCadastro would receive "0", and outside of the validation of inputs, I put the if condition(errorsCadastro == "0"), I put Ajax in, and it worked, now I did not mean to work before. I will keep looking, because something in my methods is wrong. I appreciate the help you gave me. Vlw

Browser other questions tagged

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