1
When I run the following function I always get 0 as a result.
I’d like to know why and if I’m doing something wrong.
The function cadastro_socios_xlsx receives an object and registers each instance of it in the database, accurate of the variable test (which should be incremented in a unit to each instance duly registered in the database) for a future check, but the 'test' variable only has its correct value when I put the console.log inside the request.onreadystatechange. I have tried using AJAX, but the same happens...
$(document).ready(function(){
function cadastro_socios_xlsx(tabela){
var teste = 0;
for(linha of tabela){
if(formata_cpf_cnpj(linha['CPF/CNPJ']) && valida_cpf_cnpj(linha['CPF/CNPJ'])){
if(linha['CPF/CNPJ'] == 14){
var pessoa = "fisica";
}else var pessoa = "juridica";
if (typeof linha['EMAIL'] == 'undefined') {
var email = "";
}else var email = linha['EMAIL'];
if (typeof linha['COMPLEMENTO'] == 'undefined') {
var complemento = "";
}else var complemento = linha['COMPLEMENTO'];
var data_nasc = "";
var telefone = linha['TELEFONE'].replace(" ", "");
var dados = {
"socio_nome": linha['NOME/RAZÃO SOCIAL'],
"pessoa": pessoa,
"email": email,
"telefone": telefone,
"cpf_cnpj": linha['CPF/CNPJ'],
"rua": linha['ENDEREÇO'],
"numero": linha['NÚMERO'],
"complemento": complemento,
"bairro": linha['BAIRRO'],
"estado": linha['UF'],
"cidade": linha['CIDADE'],
"data_nasc": data_nasc,
"cep":linha['CEP']
};
var dados = JSON.stringify(dados);
var request = new XMLHttpRequest();
request.open('post', './cadastro_socio.php');
request.send(dados);
request.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200){
var r = JSON.parse(this.response);
if(r){
teste++;
//console.log(teste); quando coloco o console.log aqui ele mostra os valores incrementando
}
}
}
//console.log(teste); quando coloco o console.log aqui ele sempre mostra o valor inicial da variável teste (0)
}
}
return teste; //sempre retorna 0
}
Matheus, this is happening, because a javascript request is asynchronous, so its function is returning even before the request has been completed, read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/funcoes_asynchronas and https://Developer.mozilla.org/en/Docs/Web/Javascript/Reference/Operators/await
– Daniel Mendes
Thank you, I used AJAX synchronously and it worked. But I get a message on the console saying: [Deprecation] Synchronous Xmlhttprequest on the main thread is deprecated because of its detrimental effects to the end user’s Experience. For more help, check link, actually use synchronously ends up affecting a little performance by being able to make only one request at a time, but for now will serve.
– Matheus Marqui