Success: Function(data) in Ajax not working

Asked

Viewed 719 times

0

Everything inside Success it does not execute, but the request is successfully sent because I saw inside the Chrome network and the login is done normally, it just does not trigger the ajax Success.

    function sendForm(token){
        var form_data = {
                        usuario: $('#username').val(),
                        senha: $('#password').val(),
                        captcha: token,
                        lembrar: $('#remember').val(),
                    };

    var msg = document.getElementById("msg");
    var msgu = document.getElementById("msgu");
    var msgp = document.getElementById("msgp");

        $.ajax({
                type: "POST",
                url: "includes/login.php",
                dataType: "json",
                data : form_data,
                headers: {'CsrfToken': $('meta[name="csrf-token"]').attr('content')},
                cache:false,
                    success: function(data){

                        if(data.validation_result == "success" )
                        {
                            msg.hidden = false;
                            msg.innerHTML = "Log-in realizado com sucesso!</br><font color='black'>Redirecionando em <div id='counter' style='display: inline-block;'>05</div> segundos...</font>";
                            msg.style.color = "green";
                            display();
                        }
                        else if(data.token == "incorrect" )
                        {
                            msg.hidden = false;
                            msg.innerHTML = "Token Inválido!";
                            msg.style.color = "red";
                            grecaptcha.reset();
                        }
                        else if(data.token == "invalid" )
                        {
                            msg.hidden = false;
                            msg.innerHTML = "Sistema de segurança falhou!";
                            msg.style.color = "red";
                            grecaptcha.reset();
                         }
                         else if(data.recaptcha == "incomplete" )
                        {
                            msg.hidden = false;
                            msg.innerHTML = "O captcha não foi completado!";
                            msg.style.color = "grey";
                            grecaptcha.reset();
                        }

                         else if(data.access == "blocked" )
                        {
                            msg.hidden = false;
                            msg.innerHTML = "Seu acesso está bloqueado temporariamente.";
                            msg.style.color = "grey";
                            grecaptcha.reset();
                        }

                        else if(data.validation_result == "disabled" )
                        {
                            msg.hidden = false;
                            msg.innerHTML = "Essa conta foi desativada pelo administrador.";
                            msg.style.color = "grey";
                            grecaptcha.reset();

                        }
else if( data.validation_result == "ipblock" ){
                            msg.hidden = false;
                            msg.innerHTML = "<b>Seu ip está bloqueado temporariamente.</b></br> Devido há muitas tentativas falhas de login seu acesso foi bloqueado temporariamente.</br><font color='black'><small>Tente novamente mais tarde!</small></font>";
                            msg.style.color = "red";
                            grecaptcha.reset();
                        }
                        else if( data.registration == "failed" ){
                            msg.hidden = false;
                            msg.innerHTML = "Usuário e/ou Senha incorretos!";
                            msg.style.color = "red";
                            grecaptcha.reset();
                        }
                        else if( data.form == "incomplete" ){
                            msg.hidden = false;
                            msg.innerHTML = "O usuário e/ou senha não foram preenchidos.";
                            msg.style.color = "red";
                            grecaptcha.reset();
                        }
                        else{

                        alert("Problemas no servidor. Tente novamente mais tarde!");
                 grecaptcha.reset();


                        }
                    }

                });

        return false;   
    }

Look at the message that appears, it’s normal:

Mensagem no PHP

  • The answer code was 200?

  • Do you understand that making all these codes about blocking in "success" does not make sense? The scope will only run if the return is successful (200). If it is unsuccessful, it will not run any code like this at the top, at most it would run the first block. Try using . then() after ajax.

  • Status Code: 200 OK

  • It was a success, yes.

  • Even with success Success does not work.

  • Only works with error, I just saw here, but the status is sucess of the request. How is this possible?

  • Add error after the cache:false,, thus, cache:false,error:function (jqXHR, textStatus, errorThrown) { console.log("Erro no ajax:", textStatus, errorThrown); },, then copy the result here in the comments.

Show 2 more comments

3 answers

0

After Success: Function(date), add:

        error: function(error){
            console.log('error: ' + error) //exibe na aba console do navegador
            //ou
            alert('error: ' + error) //exibe janela de texto
        }

Can help you debug.

0

Try to use the done, instead of success:

$.ajax({
        type: "POST",
        url: "includes/login.php",
        dataType: "json",
        data : form_data,
        headers: {'CsrfToken': $('meta[name="csrf-token"]').attr('content')},
        cache:false,
        ...
        }).done(function(){
           ...
        });

0

In AJAX, the success serves to identify if the request reached its destination, if it has hit the target server it will return 200 ok, because the request worked.

If it helps, you can use:

complete: function (jqXHR, textStatus) {
    console.log(jqXHR)
}

Hence you check if the Object jqxHR is coming with responseText desired.

Browser other questions tagged

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