if script condition does not recognize returned value

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";) however in the if statement of the script it does not return the alert. If I just put alert (returns); it returns the alert with the success2 value but with the if statement it does not return. Any idea what that might be?

    
asked by anonymous 19.06.2016 / 00:01

1 answer

0

The success function of $.post has to be declared within the same object where the request settings are in the success property. It also has another error: you have declared all post data on the same object. Everything you have declared for POST goes inside a data object that 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);
            }
        }
    });
}
    
19.06.2016 / 16:31