IF in Reply function POST does not work

Asked

Viewed 122 times

1

have a POST inside a javascript function and this post returns a response function 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>
  • Not working or not running? Have you checked if the value in resposta is exactly "You have been successfully logged in"?

1 answer

2


I believe there are three possibilities:

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

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

Values of the readyState:
0: request not initialized
1: server Connection established
2: request Received
3: Prepocessing request
4: request finished and Response is ready

Values of status (some)
200: OK
404: Page not found

To illustrate:

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

If it has not completed the request or the answer is not ready, it does not return 4 on readyState, if it does not find the requested page or other external problem occurs it does not return 200 in status.

Thus the function success is not executed.

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

3 - resposta=="Você foi logado com sucesso", the analysis of the answer has no treatment, ie you are reading the return as full text.

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

How do you use PHP to the webservice and AJAX for requisition I suggest the use of 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, besides encoding accents and other characters.

Preparing the reading of the 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 you helped him.

Browser other questions tagged

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