2

I am trying to get data of currency prices using API, but somehow the data is not showing on the page. In the browser, console works everything fine.

Any help is greatly appreciated. Thanks!

Output:

price: undefined

My code:

<script> $(function (){ var $data = $('#data'); $.ajax({ type: 'GET', dataType: 'json', url: 'https://cors.io/?https://www.freeforexapi.com/api/live?pairs=EURUSD', success: function(data) { console.log(data); $.each(data, function([i, price) { $data.append('<li>price: '+ price.rate + '</li>'); }); } }); }); </script> <ul id="data"></ul> 
1
  • Try price.EURUSD.rate. Or loop over data.rates. Check the returned JSON. Commented Oct 16, 2018 at 22:02

3 Answers 3

2

Made a working example for you, you have to loop the rates tag of the JSON you are getting, not the root one, like you was doing. Also, there was a lost "[" inside your code.

$(function() { $.ajax({ type: 'GET', dataType: 'json', url: 'https://cors.io/?https://www.freeforexapi.com/api/live?pairs=EURUSD', success: function(data) { console.log(data); $.each(data.rates, function(i, price) { $('#data').append('<li>price: ' + price.rate + '</li>'); }); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="data"></ul>

Sign up to request clarification or add additional context in comments.

Comments

0

The URL you're fetching doesn't return an array. The response is an object with the rates nested at the second level.

{ "rates": { "EURUSD": { "rate": 1.157282, "timestamp":1539727098144 } }, "code":200 } 

In your example, you need to access the 'rates' property on the response, and iterate over that, then access the 'rate' sub property on each curreny pair.

$.each(data.rates, function([currencyPair, rateInfo) { $data.append('<li>price: '+ rateInfo.rate + '</li>'); }); 

3 Comments

Maybe he wants it to also work when "?pairs=EURUSD" is not passed as a param, in which case it probably returns several rates (one for each "pair", whatever that means).
@Jordan Burnett Thank you!
@Jeto - had the same thought and have updated my answer.
0

A few changes, you can remove the loop and access the data object directly within your success function. Furthermore, we can improve upon readability by using Template literals

Here is the code:

$(function() { var $data = $('#data'); $.ajax({ type: 'GET', dataType: 'json', url: 'https://cors.io/?https://www.freeforexapi.com/api/live?pairs=EURUSD', success: function(data) { $data.append(`<li>price: ${data.rates.EURUSD.rate}</li>`); } }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="data"></ul>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.