Peter
Peter

Reputation: 23

API data not showing on the page

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>

Upvotes: 2

Views: 1887

Answers (3)

Calvin Ellis
Calvin Ellis

Reputation: 297

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>

Upvotes: 0

Jordan Burnett
Jordan Burnett

Reputation: 1844

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

Upvotes: 0

Shidersz
Shidersz

Reputation: 17190

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>

Upvotes: 2

Related Questions