Question

I found this SO post about currency convertions.
I am new to JSON so my question is how to send and get the result from this url into variables?

http://www.google.com/ig/calculator?hl=en&q=100GBP=?EUR 
   //this url above gives back this line under
{lhs: "100 British pounds",rhs: "115.538154 Euros",error: "",icc: true} //answer html

The url works on browser, so I tried to send by ajax call but got this error.

405 (Method Not Allowed) 
Origin http://www.mysite.com is not allowed by Access-Control-Allow-Origin.

My ajax:

var req = new Request({
    method: 'post', 
    url: 'http://www.google.com/ig/calculator?hl=en&q=100GBP=?EUR',
    onSuccess: function(response) {
        console.log(response);
    }
}).send();

I am using mootools so no jQuery please.

Was it helpful?

Solution

Google API here does not return valid JSONP (missing " in response keys) and it does not like CORS. Leaves you with either 'code your own proxy' or use somebody else's:

{lhs: "100 British pounds",rhs: "115.538154 Euros",error: "",icc: true} 

The correct response would be:

{"lhs": "100 British pounds", "rhs": "115.538154 Euros", "error": "","icc": true} 

This alternative works fine:

Request.exchange = new Class({

    Extends: Request.JSONP,

    options: {
        url: 'http://rate-exchange.appspot.com/currency?from={from}&to={to}&q={amount}',
        amount: 1
    },

    initialize: function(options){
        this.setOptions(options);
        this.options.url = this.options.url.substitute(this.options);
        this.parent();
    }

});

new Request.exchange({
    from: 'GBP',
    to: 'JPY',
    amount: '100',
    onSuccess: function(response) {
        console.log(response, response.rate, response.v);
    }
}).send();

subclassing MooTools-more's Request.JSONP to add from/to/amount and use http://rate-exchange.appspot.com api to google, which fixes their json (same data).

The above in action on jsfiddle (look at console): http://jsfiddle.net/bBHsW/

You can also use http://finance.yahoo.com/ and get csv etc.

OTHER TIPS

You have to make a backend which talks with Google API. Then you can do ajax request to your backend.

You can't do ajax request directly on Google API.

See: https://developer.mozilla.org/en/docs/HTTP/Access_control_CORS

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top