How to check if the login exists in the bank by ajax?

Asked

Viewed 679 times

-5

I made a login system with ajax and php in it I pass the login and the password that are in the database but I wanted to know what is wrong with my code because whenever I try to log into the site with a valid login it falls into my false condition and it appears that I can not redirect. gave an Alert on the return of ajax that shows the result of php page and is correct when I type the right data it brings me in an Alert that it was possible to connect what I need to do to my ajax not keep falling in false condition of my if? Obs will not post php because I tested only in php and it worked perfect the problem is in ajax

code:

$("#logar").click(function(){
          var email = $("#email").val(),
              senha = $("#senha").val();
          if(!senha){
            $('[data-toggle="tooltip"]').tooltip();
            $('#senha').tooltip('hide');
            $(".tooltip").show();
            $("#senha").focus();
            return;
          }

          $.ajax("../sys/logaradm.php",{
            type: "POST",
            data: {'usuario':email, 'senha':senha}
          }).done(function(r){
            alert(r);
            if(r==1){
            alertify.success("Acesso concedido redirecionando...");
            setTimeout("document.location = 'administracao.php'",2500);
          }else{
            alertify.error("Usúario ou senha informados nao existem!");
          }
          }).fail(function(){
            alertify.error("Ocorreu um erro durante a operacao!")
          }); 
      });

php code:

session_start();
    require "conexao.php";
    $usuario = trim(@$_POST['usuario']);

    $senha = trim(@$_POST['senha']);

    $sql_acesso = mysqli_query($mysqli, "SELECT * FROM adm WHERE email = '$usuario' AND senha = '$senha' ");
    if(mysqli_num_rows($sql_acesso) == 1 ){

        $_SESSION['usuarioSession'] = $usuario;
        $_SESSION['logadoadm']= true;
        //$_SESSION['senhaSession'] = $senha;


            echo "
                    <script type=\"text/javascript\">
                    alert(\"Login efetuado com sucesso!\");
                    window.location='administracao.php';
                    </script>";
        }
        else{
            echo "
                    <script type=\"text/javascript\">
                    alert(\"Usuario ou senha informado esta incorreto!\");
                    window.location='../admin/admin.php';
                    </script>";
        }
        mysqli_close($mysqli);
  • Your php returns what after the query?

  • what comes out in the Alert(r)?

  • if or Else if it is right it returns and redirects to the page for example can eacessar.php and in Else it goes back to the same page in opodeacessar.php

  • in Alert is leaving the result of if php and Else

  • yes, but he didn’t print the Alert first(r)?

  • type the error and so if I soon right in Alert will appear login successfully but then it falls into that ajax Lse and will not

  • yes intao he prints that I just mentioned in Alert login successfully

  • more in if you compare r == 1, and the return of r é login efetuado com sucesso?

  • r has what value? 1, 0, undefined ?

  • depends if I put the data right it will show in the login Alert successfully done if I put the wrong data it will give that the user does not exist NO ALERT ai in this if theoretically it was for him to compare the result with truth type exister do this but it does not always makes falls in that if(r==1)

  • then you must have a different return to compare in IF. 1 for successfully performed and 0 for failed authentication, or something like

  • I’ve compared it with true tbm and always fell in Else even putting the values coretos

  • intact but that’s not what I’m doing I’m comparing it to 1 if there is going to such a page or back to msm

  • rray the r and return of the done ajax function

  • I’ll go up php code to see if it helps

  • ready edited to try to make it clearer here when I type everything right as what is registered in the database in this Alert(r) it returns me that <script type="text/javascript"> Alert("Login successfully!"); window.Location='.php'; </script>";

  • and when I type everything wrong it returns it to me in Alert(r) <script type="text/javascript"> Alert("User or password entered this incorrect!"); window.Location='. /admin/admin.php'; </script>"; but even if I type everything right with ajax it brings me the true ajax condition but the php one it brings me the login successfully

Show 12 more comments

1 answer

0

The problem is that the varietal r javascript never has value 1, because the php text output is a string containing javascript.

see:

 echo "
     <script type=\"text/javascript\">
       alert(\"Login efetuado com sucesso!\");
       window.location='administracao.php';
       </script>";
 } else{
      echo "
      <script type=\"text/javascript\">
       alert(\"Usuario ou senha informado esta incorreto!\");
       window.location='../admin/admin.php';
       </script>";
}

Make php return the returned record number like this, now r may have some numeric value such as 0 or 1. In javascript(client side) do validations, Alerts and redirects.

$existe_registro = mysqli_num_rows($sql_acesso);
if($existe_registro == 1 ){
    $_SESSION['usuarioSession'] = $usuario;
    $_SESSION['logadoadm']= true;
}
mysqli_close($mysqli);
echo $existe_registro;
  • I was confused I didn’t mean what I said to myself in php is not the same thing I did?

  • @Leonardocosta you are using ajax to communicate with php and not to write javascript inside php.

  • intao I change that my line for the one that Voce made

  • @Leonardocosta, I basically created a variable and removed the Excerpts with javascript, only got the one at the end, the value $existe_registro will pass r in javascript.

  • Even so guy keeps on with the mistake

  • @Leonardocosta what mistake? When you do console.log(r) what is displayed?

  • vo ve guenta ai

  • I’m not getting anything seen by the break point that the value of it before the Alert is r=""

  • but I think it has nothing to do because I’ve used ajax so many times including in a contact form and it goes well only here that it is so

  • @Leonardocosta, I recommend putting values simulators in $usuario and $senha and access the php file through the browser and see which is the output. If you need to change the echo $existe_registro; for var_dump($existe_registro)

  • I filled the fields and ta me returning int(0)

  • @Leonardocosta, zero means that your query did not return any record

  • but as this code is not returning query and I use it to login and tested without ajax and it worked

  • right way falling into the conditions when there was login and falling into the other condition when there was no

  • solved the error I just had to give echo 1 in my if in php and echo 0 in Else so he compared

  • @Leonardocosta, that was the goal of $existe_registro that was the number of rows returned by the query.

Show 11 more comments

Browser other questions tagged

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