Function in jQuery Ajax does not return Value

Asked

Viewed 150 times

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 how can I fix this?

  • Do everything inside the Success, when the API returns the values.

  • @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 another div id

2 answers

1

Fell for the trick of the async.

What happens and what part of ajax takes a little longer to execute, when it comes to your return valor; the request is still being processed.

That stretch valor = formata(valorconvertido); only performs well after the function has already been executed, and a little confused at first I know.

Imagine that the $ajax runs in parallel, even after its function has finished the request continues "live".

Try to study some terms like callback, async, await, async function.

For now to solve your problem would be something like this

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);	
			//document.write(formata(valorconvertido));
			
			valor = formata(valorconvertido);
			$("#valorreal").html(valor);
		}
	})
}
    
//nao e uma boa pratica declar uma funcao dentro da outra
function formata(v){
  return parseFloat(v).toLocaleString("pt-BR", { style: "currency" , currency:"BRL"});
}

converterreal(100)
<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>

  • By clicking Run, the converted value is not being displayed.

  • @Wendell probably by not falling in the success, this is happening because it has reached its request limit in the api. It is returning this answer {"status":400,"error":"Free API limit reached."}

  • suggest to edit the question and take the parameter apiKey of the URL

  • Would there be any way for the API request to return only the value of the currency? (For example, 1 Yuan is equal to 0.56 real) So I would use this value that returns in other formulas without having to request the API

0

This is because you are giving return before the value is set by the function, since it is asynchronous. One way to solve the problem would be to change the field value within the function, or add the functions done and fail to your ajax so that they return the value only when it is set.

Method 1:

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));

            $("#valorreal").html(formata(valorconvertido));
        }
    });      
}

Method 2:

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'
    })
    .done((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));

        return formata(valorconvertido);
    })
    .fail(() => {
        return 0;
    });      
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.