Asynchronous request
When you execute a method in Ajax you are performing an asynchronous request, created implicitly by the object XMLHttpRequest . This function is waiting for a response, meaning that as long as you do not receive it, nothing you put in the success parameter or any other callback will run. In other words, when you perform an asynchronous request, it is not executed immediately.
In your code console.log(emailPessoa);
is running before your request returns a response, in case success . This happens with anything you put outside the scope of the response method.
var emailPessoa = '';
$.ajax({
url: api/aluno/id,
type:'GET',
success: function(r){
emailPessoa = r[0].email;
console.log(emailPessoa); // saida-exemplo: [email protected]
}
});
console.log(emailPessoa) // isso vai ser executado antes do ajax
var teste = "Teste"; // Isso também
// essa funcao vai ser declarada
function funcaoTeste(){
console.log("Executou funcaoTeste");
};
// essa funcao também foi executada antes do ajax
funcaoTeste();
Your emailPessoa
variable will only change after the request gets a response. When you run console.log(emailPessoa)
it simply displays what you set in the variable above: ''
, that is, nothing.
This link clearly explains the difference between Synchronous and Asynchronous methods and requests .