Problem passing some Json messages to Jquery

Asked

Viewed 72 times

0

Guys, I have a form that is passed to my PHP via Ajax in Jquery and returns the result via Json to my console. Follow a snippet of code in PHP.

if($tabela == 'setup') {

    if(isset($_POST['nome'])){
        $nome = $_POST['nome'];
        if(strlen($nome) < 6) {
            $res['resultado'] = "inv";
            $res['campo'] = "nome";
            $res['mensagem'] = "Nome muito curto";
        } else {
            $sql = "UPDATE professores SET nome='$nome' WHERE idprofessor = $meuid";
        }
    } else if(isset($_POST['email']) and isset($_POST['telefone'])){
        $email = $_POST['email'];
        $telefone = $_POST['telefone'];
        if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $sql = "UPDATE professores SET email='$email',telefone='$telefone' WHERE idprofessor = $meuid";
        } else {
            $res['mensagem'] = "E-mail inválido.";
        }

    } else if(isset($_POST['senha_nova'])){
        $res['ok'] = "senha";
        $senha_atual = md5($_POST['senha_atual']);
        $busca_atual = $pdw -> prepare("SELECT senha FROM professores WHERE idprofessor = $meuid AND senha = '$senha_atual'");
        try {
            $busca_atual -> execute();
            $res['resultado'] = "ok";
            $res['mensagem'] = "Dados retornados";
        } catch(PDOException $e) {
            $res['resultado'] = "erro";
            $res['mensagem'] = $e->getMessage();
        }
        if($busca_atual->rowCount < 1) {
            $res['resultado'] = "ok";
        } else {
            $senha_nova = $_POST['senha_nova'];
            $senha_confirma = $_POST['senha_confirma'];
            // comparar senhas
            //$sql = "UPDATE professores SET senha=".md5($senha_nova)." WHERE idprofessor = $meuid";
            $res['sql'] = $sql;
        }
    };
    if($sql) {
        $atualiza = $pdw -> prepare($sql);
        try {
            $atualiza -> execute();
            $res['resultado'] = "ok";
            $res['mensagem'] = "Dados atualizados com sucesso";
        } catch(PDOException $e) {
            $res['resultado'] = "erro";
            $res['mensagem'] = $e->getMessage();
        }
    }
}
echo json_encode($res);

Then you have the code to run the update via PDO and the echo json_encode($res);

If the user types more than 6 characters in the text box, it performs correctly and prints in the log console correctly. But typing less does not return the error message as expected.

I did the test by placing the form directly on this ajax.php page and it displays the messages correctly, but for Jquery it will not.

Follow code from Jquery

    $('form').on('submit', function(e){
    e.preventDefault();
    var formulario = $(this).attr('name');
    var acao = $(this).attr('action');
    var dados = $(this).serialize();
    $('input.validate').removeClass('invalid');
    $.ajax({
        url: 'ajax/geral.php?act='+acao+'&tbl='+formulario,
        dataType: 'json',
        data: dados,
        type: 'post',
        success: function(data){
            if(data.resultado == 'ok') {
                M.toast({html: data.mensagem});
            } else if(data.resultado == 'erro') {
                M.toast({html: "Ocorreu um erro ao atualizar dados."});
                console.log(data.mensagem);
            } else if(data.resultado == 'inv') {
                M.toast({html: data.mensagem});
                $('input.validate#'+data.campo).addClass('invalid');
            }
            console.log(data);
        },
    })

})

Curious fact is that if I put SQL in the first conditional block and type less than 6 characters, it executes the query and prints in the log.

  • Can you put your full code? I believe it will be easier to locate the problem.

  • The site is not letting me post the entire code, stating it is too long.

  • I was able to edit the original post and put the complete code. Ignore this part of the email and password, as they are not yet ready. Although it also does not display the error message if the password is wrong..

1 answer

-1

Within the if() that checks if the name is short, also goes a

echo json_encode($res)
  • 1

    I’ve done it and not solved. Even my echo is at the end of the code and takes all other messages.

  • then passes the whole code so gnt can see what you’ve done and what the problem is

  • 1

    The site won’t let me post the entire code, saying it’s too long.

  • but at least that part passes

  • 1

    I was able to edit the original post and put the complete code. Ignore this part of the email and password, as they are not yet ready. Although it also does not display the error message if the password is wrong..

  • Check the json returns?

  • 1

    I forgot to put together because there are other irrelevant codes. But it is after closing the last key.

  • I understand, but if you put echo there inside the key of the error still yes no?

  • 1

    Exactly. It still doesn’t work. It’s really very strange.

  • I managed to fix it. Just put a@ in the if($sql) conditional, staying if(@$sql)

Show 5 more comments

Browser other questions tagged

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