Variable value does not change inside ajax

0

I'm trying to assign a value to a variable within the success of an ajax, however, when checking the value of that variable, this value is with the creation value of the variable,

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) // saida: ''

Did you get the problem? What am I doing wrong?

    
asked by anonymous 08.05.2018 / 22:18

2 answers

2

By default, this call is asynchronous. This means that you can not access the value that way.

As it's a rather lengthy topic to write in this answer, follow a link that explains everything you need to know.

AJAX synchronous and asynchronous requests in jQuery

Note: Complementing the link, synchronous calls often block execution while the request is in progress, so be careful.

I hope I have helped!

    
08.05.2018 / 22:22
1

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 .

    
08.05.2018 / 22:41