whereas is just trying to access a variable outside the scope or is facing an asynchronous request problem:
Access out of scope:
If you are trying to access a variable that is outside the scope of the function where you want it, you can declare it in a scope to which both functions have access, as in the example:
var DI = ''; // inicializando com um valor vazio, para que não ocorra um acesso a uma variável não inicializada
$(document).ready(...
And you can still use the value of the same variable in another function after having populated it.
Asynchronous request:
If the problem is accessing the variable outside the scope of the request because it has no value (but had already been declared in an external scope), you can make a synchronous request as follows on jQuery
:
$.ajax({
url: "https://www2.cetip.com.br/ConsultarTaxaDi/ConsultarTaxaDICetip.aspx",
async: false // fazendo com que a requisição seja síncrona; Não haverá execução até que o processo dessa função termine.
}).done(function (response) {
var data = JSON.parse(response);
$('#taxaPct').text(data.taxa + '%');
DI = data.taxa;
});
Note that I am not using then
and yes done
, given that then
returns a new Promise (would continue to be treated later, asynchronously). By making nothing else happen until the request is completed, you should be able to popular the variable the way you need it. This is because the requisition is occurring in another "process", while its main code continues running. So when arriving at the use of its variable DI
, it has not yet been populated, ie the request has not yet received a response.
Another detail that can lead to problems is the fact of having the call inside the [$(document).ready
], because it may be that the function that makes use of its variable DI
has already been called but the page has not yet fully loaded. The function will only be called on full charge of GIFT.
That being said, I recommend that you review the code to avoid synchronous calls when possible, as all the code will wait for the call to finish to continue and this is bad for the user experience, giving the impression that something "stuck". You should see a message like the one below in your browser console when using calls like:
[Deprecation] Synchronous Xmlhttprequest on the main thread is
deprecated because of its detrimental effects to the end user’s
Experience. For more help, check https://xhr.spec.whatwg.org/.
Error in browser console?
– Dakota
thanks to all, I used the asynchronous request and it gave very good.
– user2537274
Hello, is that question has already been answered
– Wallace Maxters