Declaration and use of variables usuario and senha are occurring in different scopes.
To understand what is happening I prepared a simplified example replicating the same error:
function teste() {
(function() {
var variavelLocal = 33; // a variavelLocal tem sua visibilidade restrita a
// função anônima.
})();
console.log(variavelLocal); // Aqui vai dar ERRO o método console.log()
// não consegue enxergar a definição da variavelLocal
}
teste();
In this first example the variavelLocal is visible only within the scope in which it has been declared.
To correct it is sufficient to declare variavelLocal in a broader context:
function teste() {
var variavelLocal; // A variavelLocal é declara dentro do contexto da função teste.
(function() {
variavelLocal = 33; // Nesse casoa palavra chave var deve ser retirada pois não
//queremos outra variável local a função anônima
})();
console.log(variavelLocal); // Funciona
}
teste();
To correct your code is to apply the same principle:
function login() {
// usuario e senha declarados no escopo mais elevado dentro login()
var usuario;
var senha;
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM usuarios', [], function (tx, resultado) {
let rows = resultado.rows;
for (var i = 0; i < rows.length; i++) {
// Importante aqui retirar a palavra-chave var para que possamos atribuir
// valor ao invéz de redeclarar usuario e senha como variáveis locais
// dentro de um escopo mais interno.
usuario = rows[i].usuario;
senha = rows[i].senha;
}
alert("Aqui funciona: " + usuario);
});
});
// Agora usuario e senha são visíveis
if (($("#usuario").val() == usuario) || ($("#senha").val() == senha)){
window.location='painel.html';
}else{
alert("Agora funciona: " + usuario);
}
}
You are declaring the variables
usuarioandsenhawithin afunction, and with that these variables will have restricted scope within thisfunction. Put theif...elsewithin itfunction, shortly after thefor. Because I believeifis executed before the query to Websql, and with that the variables even exist yet, and even if they existed, would not have the values of the query to the bank.– Sam
@Sam, what’s the right way to do this?
– Tiago