IF on POST response function does not work [closed]

1

I have a POST inside a javascript function and this post returns a function answering the problem and that the IF in the response function is not working

<script>
$(document).ready(function(){
    $("#mlogin" ).click(function() {
        $("#modallogin").modal({                    // wire up the actual modal functionality and show the dialog
                "backdrop"  : "static",
                "keyboard"  : false,
                "show"      : true                     // ensure the modal is shown immediately
        });
    });
    $("#btncancel" ).click(function() {
        $("#modallogin").modal("hide");
        $("#msg_login").html("");
    });
    $("#btnok" ).click(function() {
        var usuario = $('#usuario').val();
        var senha = $('#senha').val();
        var acao= "login";
        var startaction=1;
        $.post('controllers/clogin.php', {usuario:usuario , senha:senha, acao:acao, startaction:startaction}, function(resposta) {//enviamos o parametro nome, com o valor da variavel nome criada acima
                    //location.reload();
        $('#usuario').val(""), $('#senha').val(""), acao="", startaction=0;
            $("#msg_login").html(resposta);
            // O if abaixo não está funcionando
            if (resposta=="Você foi logado com sucesso"){
                $("#modallogin").modal("hide");
                $("#msg_login").html("");
            }
        });
    });
});
</script>
    
asked by anonymous 16.01.2015 / 04:41

1 answer

2

I believe there are 3 possibilities:

1 - The function function(resposta){} of your code represents the parameter success of the function $.post;

This means that it only executes if the function succeeds, that is, the third parameter of the function, object jqXHR , has the following values: jqXHR.readyState = 4 e jqXHR.status = 200;

ReadyState values:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

Status values (some)
200: OK
404: Page not found

To illustrate:

function(resposta, StringSucesso, retorno){
     console.log(retorno.status);
     console.log(retorno.readyState);
}

If he did not finish the request or the answer is not ready, he does not return 4 in readyState , if he does not find the page requested or another external problem occurs he does not return 200 in status.

In this way the success function is not executed.

2 - The function breaks or exits before if : if there is a return, the following return code will not be executed. If an error of javascript occurs before if , the following code also does not execute.

3 - resposta=="Você foi logado com sucesso" , the response analysis has no processing, ie you are reading return as fulltext.

It is not a good practice, and I say it is a bad practice mainly for us who speak Portuguese, since our language has an accent.

How do you use PHP for webservice and AJAX for request I suggest using JSON :

Preparing the code to be returned by PHP :

 $array = Array();
 $array['sucesso'] = 1 // valor varia 1 ou 0, 1 para sucesso e 0 para erro
 $array['mensagem'] = "Você foi logado com sucesso" // A mensagem retornada pelo webservice
 echo json_encode($array);

The function json_encode , transforms the array into text json , in addition to encoding accent and other characters.

Preparing to read return in Javascript :

try{
      var objResponse = JSON.parse(response);

      if(objResponse.sucesso == 1){
    // Executa o código de sucesso
        console.log(objResponse.mensagem);
      }else{
    // Executa o código de erro (negação)
        console.log(objResponse.mensagem);
      }


}catch(e){
    // Faz o tratamento da exceção (e);
}

I hope to help you.

    
16.01.2015 / 08:18