Asynchronous request
When you execute a method in Ajax you are performing an asynchronous request, implicitly created by the object Xmlhttprequest. This function is the waiting of a reply, it means that while you do not receive it, nothing you put in the parameter Success or in any other callback will be executed. In other words, when you perform an asynchronous request it is not executed immediately.
In its code the console.log(emailPessoa);
is being executed before your request returns a reply, in case Success. This happens to anything you put out of 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 variable emailPessoa
will only be changed after the request gets a response. When you execute console.log(emailPessoa)
it simply displays what you set in the variable up there: ''
, that is, nothing.
At this link clearly explains the difference between Synchronous and Asynchronous methods and requests.
That question can help you. You need to understand a little bit about synchronous and asynchronous methods.
– bio
When you open a website it takes a while to load, even if it’s a few seconds or a fraction of seconds, right? Ajax is the same thing, it will "open" another page to then return something. While Ajax is calling the other page, its
console.log
outside Ajax has already "worked" and gone to sleep. When Ajax comes back with the value, theconsole.log
had already been executed. That’s why the name is Ajax (XML and Asynchronous Javascript).– Sam