AJAX returns the same answer

Asked

Viewed 39 times

0

I have a login form with PHP and JQUERY:

index php.:

   <form action="." method="POST" class="form-signin">
      <h1 class="h3 mb-3 font-weight-normal">Entrar</h1>
      <label for="name" class="sr-only">name</label>
      <input type="text" id="name" name="name" class="form-control" placeholder="Usuario...">
      <label for="word" class="sr-only">Password</label>
      <input type="password" id="word" name="password" class="form-control" placeholder="Senha...">
      <button style="margin-top: 50px;" id="login" class="btn btn-style btn-lg btn-primary btn-block"><strong>Logar</strong></button>
      <div style="margin-top: 35px;">
      <div id="add_err" class="card">
      </div>
      </div>
    </form>

login js.:

$(document).ready(function(){
    $("#add_err").css('display', 'none', 'important');
     $("#login").click(function(){  
          username=$("#name").val();
          password=$("#word").val()
          $.ajax({
           type: "POST",
           url: "login.php",
           data: "name="+username+"&pwd="+password,
           success: function(html){    
            if(html=='true')    {
             $("#add_err").html("right username or password");
             //window.location="../index.php";
            }
            else    {
            $("#add_err").css('display', 'inline', 'important');
            $("#add_err").html("<font style='margin-top: 50px; padding: 20px; background-color: #C70039; color: white; border-width: 0px;'>Usuario o Senha incorretos</font>");
            $("#login").html('<strong>Logar</strong>');
            }
           },
           beforeSend:function()
           {
            $("#login").html("<div class='spinner'><div class='bounce1'></div><div class='bounce2'></div><div class='bounce3'></div></div>");
            $("#add_err").css('display', 'none', 'important');
            $("#login").blur();
           }
          });
        return false;
    });
});

login.php:

    sleep(3);
    session_start(); 
        //Incluindo a conexão com banco de dados   
    include_once("../assets/php/config.php");    
        $usuario = mysqli_real_escape_string($con, $_POST['name']); //Escapar de caracteres especiais, como aspas, prevenindo SQL injection
        $senha = mysqli_real_escape_string($con, $_POST['pwd']);
        $senha = md5($senha);

        //Buscar na tabela usuario o usuário que corresponde com os dados digitado no formulário
        $result_usuario = "SELECT * FROM admin WHERE name = '$usuario' && password = '$senha' LIMIT 1";
        $resultado_usuario = mysqli_query($con, $result_usuario);
        $resultado = mysqli_fetch_assoc($resultado_usuario);

        //Encontrado um usuario na tabela usuário com os mesmos dados digitado no formulário
        if(isset($resultado)){
            echo "true";
            $_SESSION['ID']             = $resultado['id'];
            $_SESSION['NAME']           = $resultado['name'];
            $_SESSION['PASSWORD']       = $resultado['password'];
            $_SESSION['LEVEL']          = $resultado['level'];
            }else{
                echo "false";
            }

The script does the query in the database and returns, if it is found it returns 'true' and displays the success message, if not found it returns 'false' and the error message, the problem is that regardless of the result of the query 'true' or 'false' it displays the error message!

  • And what would this error message be? Is this message not actually a warning message (Warning)? Because if it was a real error message, an unforeseen exception, your code would probably have stopped running even before printing "false";

  • @user140828 The error message is the one that appears when the user or password are incorrect!

  • Yes, but what would that message be? Is it generated by you or PHP? What is written on it? These points help to discover the reason for the error, but you have not posted where this message comes from, there is no way to help just knowing that somewhere there is an error message that we do not know how it is generated and what its content.

  • @user140828 Oh, yes... It is generated in javascript (login.js). no if and Else (incorrect user or password)! I debug the script and it is said that he did the query and got the return, IE the code is not stopping before

  • Make a console.log(html); before if(html=='true') { and post here to see...

  • @Correct user and password Lipespry: console.log(HTML) = 'true'. Incorrect user and password console.log(HTML) = 'false'. working normally, I believe the problem is in AJAX but I’m not able to find!

  • Bro. Seu if/else are working. I played, in part, your problem. I made a PHP page with echo 'true'; / echo 'false'; and AJAX worked perfectly. Even in if/else. Is there any more code in there that might be influencing?

  • @Lipespry no other code! which version of jquery you used ? you can post your code so I can test ?

  • 1

    Yes, I can! Later, if there is no solution here, put for you. I am in the cell now (away from the PC).

Show 4 more comments

1 answer

0


Although I did not find any logical error in your code:

"- you can post your code so I can test ?"


As the server’s responsibility is only to respond true or false, used admin/admin in order to test. Nothing prevents you from using your own script.

login.php:

<?php
    //sleep(3);
    if (
        $_POST['name'] == 'admin'
        && $_POST['pwd'] == 'admin'
    )
        echo 'true';
    else
        echo 'false';

On the HTML page, I did nothing but organize. But I think it’s important to post so you can check the header scripts and make it easy to play. You can even take advantage of the code, since it’s more organized.

index php.:

<!DOCTYPE html>
<html>
    <head>
        <title>Login com AJAX</title>
        <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
        <script src="login.js"></script>
    </head>
    <body>

        <form class="form-signin">
            <h1 class="h3 mb-3 font-weight-normal">Entrar</h1>
            <label for="name" class="sr-only">Name</label>
            <input
                type="text"
                id="name"
                name="name"
                class="form-control"
                placeholder="Usuario...">
            <label for="word" class="sr-only">Password</label>
            <input
                type="password"
                id="word"
                name="password"
                class="form-control"
                placeholder="Senha...">
            <button
                style="margin-top: 50px;"
                id="login"
                class="btn btn-style btn-lg btn-primary btn-block">
                <strong>Logar</strong>
            </button>
            <div style="margin-top: 35px;">
                <div id="add_err" class="card"></div>
            </div>
        </form>
    </body>
</html>
<!-- por LipESprY -->

Already in Javascript, I had the pleasure of almost disable jQuery on your page. I only kept the part of jQuery AJAX, which is one of the few methods of it that I still recommend using.

Remember that I kept "practically all" the structure and logic of your code. In the end, you should get visibly the same result. I won’t go into too much detail, the code is very easy to understand...

login js.:

document.addEventListener(
    'DOMContentLoaded',
    function(){

        let dvErro = document.getElementById('add_err');
        let btn = document.getElementById('login');

        btn.addEventListener(
            'click',
            function(ev){
                ev.preventDefault();

                let username = document.getElementById('name').value;
                let password = document.getElementById('word').value;

                $.ajax({
                    url: 'login.php',
                    method: 'post',
                    data: {
                        name: username,
                        pwd: password
                    },

                    beforeSend: function(){
                        dvErro.style.display = 'none';
                        btn.innerHTML = (
                            '<div class="spinner">'
                            +'<div class="bounce1"></div>'
                            +'<div class="bounce2"></div>'
                            +'<div class="bounce3"></div>'
                            //+'spinner' // Para reprodução
                            +'</div>'
                        );
                        btn.blur();
                    },

                    success: function(resposta){
                        dvErro.style.display = 'inline';

                        if (resposta == 'true') { // Login OK
                            dvErro.innerHTML = 'right username or password';
                            // Redireciona:
                            //window.location.href = 'index.php';
                        } else if (resposta == 'false') { // Login ERRO
                            dvErro.innerHTML = (
                                '<font style="'
                                +'margin-top: 50px; padding: 20px; '
                                +'background-color: #C70039; '
                                +'color: white; border-width: 0px;">'
                                +'Usuario ou Senha incorretos'
                                +'</font>'
                            );
                            btn.innerHTML = '<strong>Logar</strong>';
                        } else { // Notifica caso receba alguma outra resposta
                            console.log(resposta);
                            alert('Servidor retornou resposta inválida.');
                        }
                    },

                    error: function(erro){
                        console.log(erro);
                        alert('Erro no AJAX - detalhes no console.');
                    }
                });
            },
            false
        );
    },
    false
);

Note: it is not a bad idea to upgrade to version 3.3.1 of jQuery, which is the latest in the library. There is little difference in the syntax of jQuery AJAX, but nothing difficult to implement... Take a look at documentation.


Finally, this is the result:

demonstracao

The material of that reply is available in my Github/lipespry.

Browser other questions tagged

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