Javascript function returns wrong Ajax

0

I am validating a registration with JS.

There's a part like this:

...
if( existUser() ){
   alert(' Email já cadastrado.');
}
else // ok , envia formulario !

The function Js that checks whether the user exists, calls a PHP, accesses the database, and whether or not a true or false string exists, respectively.

function existUser(){
 var e = document.getElementById('email').value;
    var ajax = getAjax(function(){
        if (ajax.readyState==4 && ajax.status==200){
            return ajax.responseText=="true";    // retorno correto
        }
    });
    ajax.open("GET","busca.php?email="+e,true);
    ajax.send();
    return true; // a rotina esta caindo aqui dando retorno errado
}
  • If in the final return I put True, it says that there is an email that does not exist
  • If I leave False, it says that there is no email that exists
  • and tested it until null or no return on that end. There is an existing email address.

  • I know I can do this check in PHP before playing in the bank, but I want to do it in Javascript.

  • If anyone can give an opinion thank you.

UPDATED: Thank you for the explanations, I was able to understand why it did not work!

I have achieved a partial solution, here I share with everyone. I could not get the variable directly for the check (if), but I did a bad thing.

When I receive the PHP string, inside ajax I keep the variable in a hidden input ( input[type=hidden] )

  <input  type="hidden" name="rs" id="rs" value="">

and js:

...
if (ajax.readyState==4 && ajax.status==200){
        document.getElementById('rs').value = ajax.responseText; //guarda valor
        }
   });
    ajax.open("GET","busca.php?email="+e,true);
    ajax.send();
    return document.getElementById('rs').value.toString()=="true"; // o obtêm 
}

In the email field I put an event to call the function when the user finishes typing the email

  <input  type="text" name="email" id="email" onblur="existUser()">

So, PHP is already called before the user clicks send.

In the Javascript treatment maintained the same

...
if( existUser() ){
   alert(' Email já cadastrado.');
}
else // ok , envia formulario !

When the user clicks and executes the routine again, they will have time to have done a check and save in the input. I ran several tests here and it worked.

But to leave complete and more "armored" I will do this treatment in PHP also not to register with repeated email: +)

Thanks!

    
asked by anonymous 26.03.2017 / 18:54

0 answers