Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 77

Return false success in $.ajax jQuery

I'm using jQuery version 1.6.2 and I can't redirect my users to the main page after login. Actually, I can, but if I do this, I can't display the "error messages".

Can you help me?

My jQuery code:

$(".enviar").click(function() {
    var email = $(".postEmail");
    var setEmail = email.val();
    var senha = $(".postSenha");
    var setSenha = senha.val();

    $.ajax({
        url: "actions/logar.php",
        async: false,
        cache: false,
        type: 'POST',
        data: "email="+ setEmail +"&senha="+ setSenha,
        success:function(data){
            if(data == 'true'){
                window.location.href="home";
            } else {
                $(".resposta").html(data);
            }
        }
    });
    return false;
});

Where ".enviar" is my submit button and ".resposta" is the div where I'll display the error message.

My PHP code:

        if(!$AccountDAO->Registrado()){
            $postEmail = addslashes(strip_tags(trim($_POST['email'])));
            $postSenha = addslashes(strip_tags(trim($_POST['senha'])));

            if ( !preg_match( '/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/', $postEmail )){
                echo '<span class="error">O seu e-mail parece inválido</span>';
                exit();
            } elseif ( strlen($postSenha) < 4 ) {
                echo '<span class="error">Digite uma senha com quatro ou mais caracteres</span>';
                exit();
            } 

            $validarUsuario = $SQL->prepare("SELECT * FROM `c_usuarios` WHERE `email` = :email AND `senha` = :senha");
            $validarUsuario->bindParam( ':email', $postEmail, PDO::PARAM_STR );
            $validarUsuario->bindParam( ':senha', hash('sha512', $postSenha), PDO::PARAM_STR );
            $validarUsuario->execute();

            if( $validarUsuario->rowCount() == true ){

                $dadosUsuario = $validarUsuario->fetch(PDO::FETCH_ASSOC);
                $_SESSION['uid'] = $dadosUsuario['uid'];
                echo 'true';

            } else {

                echo '<span class="error">O e-mail ou a senha estão incorretos</span>';

            }
        }
?>

I already try "return true" instead of "echo "true"", but i get the same result: nothing. =(

Alright, sorry 4 my english (I'm Portuguese, as you can see) and this is my first time without Google Translate. Ah, if is possible too, rate my language skills, please? HAHAH

Ok, seeya!

Update

After many debbugings(?), I came to the conclusion that all the code that follows

            $dadosUsuario = $validarUsuario->fetch(PDO::FETCH_ASSOC);
            $_SESSION['uid'] = $dadosUsuario['uid'];

doesn't execute. Indeed, the "true" (from echo) execute normaly, but the "true" (string) has a line break. See:

screenshot

I don't understand! :S If I move the `echo true´ to the top of my source, it displays normally, without line break.

Upvotes: 2

Views: 11048

Answers (2)

Ruslan Polutsygan
Ruslan Polutsygan

Reputation: 4461

Are there any avascript errors? Are you using Firebug or Google Chrome console? If yes try to log your response without any redirection. I've written simple ajax-request and according to the response make(or do not) redirect. All works fine. Html:

<div id="wrapper">
    <form action="">
        <input type="submit" id="submit" />
    </form>
</div>

JS:

$('#submit').click(function(){
                $.ajax({
                    url: "ajax.php",
                    async: false,
                    cache: false,
                    type: 'POST',
                    data: "show=1",
                    success: function(data){
                        if(data=='true'){
                            window.location.href="other-page.html";
                        } else {
                            $("#wrapper").append(data);
                        }
                        console.log(data);
                    }
                });
                return false;
            });

And very simple PHP:

if($_POST['show']==1)
    echo 'true';
else
    echo '<span class="error">Error</span>';

Whatever, try to debug response from your server. Sorry for lots of code, but can't see important difference between your and my ones. Maybe you will.:) I hope it will be helpfull.

Upvotes: 2

Maxime Fafard
Maxime Fafard

Reputation: 376

Try to add the domaine name. Like window.location.href="http://example.com/home";

Upvotes: 0

Related Questions