If script condition does not recognize returned value

Asked

Viewed 52 times

0

Hello, I have following code:

function addUser(value){

var adduser = value;
var useremail = localStorage.getItem('email');
var userpassword = localStorage.getItem('password');
var acao = "adicionar";


$.post('http://localhost/app/searchplayer.php', {useremail : useremail, userpassword : userpassword, acao : acao, adduser : adduser}, function(retorna){

    if(retorna == "sucesso2"){

    alert (retorna);

    }

}); 

}

and the php code I have a single echo that returns success2 (echo "success2";) but in the if condition of the script it does not return the Alert. If I just put Alert(returns); it returns the alert with the value success2 but with the condition if it does not return. Any idea of what might be?

  • Sorry, but what is the return value? How about putting a "}Else{Alert('what is the return value?')}; See what happens?

  • 1

    Maybe it’s a space you have and can’t see. Try if(retorna.trim() == "sucesso2") {....

  • @Magichat - It returns the echo value on a php page, which in this case is success2.

  • @Miguel tested with <code>if(returns.Trim() == "success2") {.... <code> and it worked. Now the question of being a space, apparently there is none. What would be the function . Trim()? thank you

  • The Trim function, present in several languages removes spaces present in the ends and uses string, whether spacing at the beginning or end of the string.

1 answer

0

The success function of $.post has to be declared inside the same object where the request settings go, in the property success. There is also another error: you have declared all posting data on the same object. Everything you declared for the POST goes inside an object data which is inside the same object where the request settings are. The solution code is below:

/**
 * Adiciona um usuário.
 * @param number value
 */
function addUser(value){
    // Organização de dados
    var user = {
        add: value,
        email: localStorage.getItem('email'),
        password: localStorage.getItem('password'),
        action: "adicionar"
    };

    // Envia uma requisição para o servidor.
    $.post("http://localhost/app/searchplayer.php",
    {
        // Dados que vão para a requisição.
        data: {
            useremail : user.email,
            userpassword : user.password,
            acao : user.action,
            adduser : user.add
        },

        // Callback de sucesso
        success: function(response) {
            if(response === "sucesso2") {
                alert(response);
            }
        }
    });
}

Browser other questions tagged

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