0
I am making a conversion from Brazilian Currency (Real) to Chinese Currency (Yuan). I am using the website API: https://free.currencyconverterapi.com
. When debugging in the browser, I can see that the Ajax function with the API request is working, but when it returns the variable valor
in the penultimate line of the code, the value returned is not being the converted value but the original value, follows the code:
function converterreal(valor){
var moeda = 0;
var valor = valor;
var valorconvertido = 0;
$.ajax({
url: 'https://free.currencyconverterapi.com/api/v6/convert?q=BRL_CNY&compact=ultra&apiKey=873041c527593ec7e31e',
dataType: 'jsonp',
success: function(data) {
moeda = data.BRL_CNY;
console.log(moeda);
valorconvertido = (moeda*valor);
function formata(v){
return parseFloat(v).toLocaleString("pt-BR", { style: "currency" , currency:"BRL"});
}
//document.write(formata(valorconvertido));
valor = formata(valorconvertido);
}
})
return valor;
}
var testevalor = converterreal(400);
$("#valorreal").html(testevalor);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>O valor em real é: <span id="valorreal"></span> BRL<br>
You are calling the function at runtime, but Ajax is asynchronous and does not return the value of
success
at the same time.– Sam
@Sam how can I fix this?
– Wendell
Do everything inside the Success, when the API returns the values.
– Sam
@Sam this function will return values in several
div
, i tried to put everything inside the sucess, besides not having returned any value, I do not know how to use the same function in anotherdiv id
– Wendell