Javascript function returns wrong Ajax

Asked

Viewed 150 times

0

I’m validating a register with JS.

There’s a part like this:

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

The Js function that checks whether the user exists, calls a PHP, accesses the database, and whether or not it echoes a string "true" or "false", 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 it as False, it says that there is no email that exists
  • and tested until leaving null or no return on that end. Ai cadastra existing email.

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

  • If anyone can give an opinion I’d appreciate.


UPDATED: People, Thanks for the explanations I could understand why it didn’t work.!

I got a partial solution here, I share it with everyone. I could not get the variable directly, for checking (if), but I made a trick.

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

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

and you:

...
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 (input) email field I placed an event to already call the function when the user finishes typing the email

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

Thus, it is already called PHP before the user click submit.

In Javascript I maintained p same

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

When the user clicks and runs the routine again, he will already have time to have a check and saved the input.
I performed 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 !!

  • ajax executes asynchronously and the way Voce made this structured synchronously... Oce needs to execute the return of message or sending form ... within the return of your ajax response

  • you must use a callback function to catch the return. Here a related response: http://answall.com/questions/188577/

No answers

Browser other questions tagged

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