Noah-1
Noah-1

Reputation: 396

How to retrieve exchange rates with Javascript?

I am trying to get a simple exchange rate from USD to MXN using yahoo api but Im not getting anything back, is this just a CORS issue again or am I accessing the property incorrectly?

var exchangeRateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%29&env=store://datatables.org/alltableswithkeys";

//Get current USD->MXN exchange rate
$.getJSON(exchangeRateURL, function(data) 
    {   
        priceInMXN = data.query.results.rate.Rate;
        document.write(priceInMXN);

    });     

Thanks in advance!

Upvotes: 0

Views: 3994

Answers (2)

ryanlutgen
ryanlutgen

Reputation: 3051

Pass a param to return JSON (&format=json):

var exchangeRateURL = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%29&env=store://datatables.org/alltableswithkeys&format=json"

$.getJSON(exchangeRateURL, function(data) {
  console.log(data.query.results.rate.Rate);
});    

Upvotes: 3

Marty
Marty

Reputation: 39466

You're fetching XML, not JSON. Something like this will work:

$.get(exchangeRateURL, function(data) {
    console.log($(data).find('Rate').text());
});

Upvotes: 3

Related Questions