Ace
Ace

Reputation: 1467

jQuery Ajax Request to get JSON data fires error event

I'm trying to make an ajax request to a Google API, to get JSON data of current exchange rate.

My code so far:

$.ajax({
    url: "http://www.google.com/ig/calculator?hl=de&q=1USD=?EUR"
}).done( function ( data ) {
    var obj = $.parseJSON( data )
    alert( data.rhs );
});

The link for the google api is http://www.google.com/ig/calculator?hl=de&q=1USD=?EUR

my problem is that my code doesn't fire the done function.

I know there is missing something, maybe some params?


UPDATE

here is my new code that i've found somewhere:

    function forex(val, from, to, callback) {
        $.ajax({
            url: 'http://www.google.com/ig/calculator?hl=en&q='+val+from+'%3D%3F'+to,
            type: 'GET',
            datatype: 'string',
            success: function(data) {
                var json = eval("(" + data+ ")"), output;
                if (typeof json == 'object' && json.rhs) {
                    output = json.rhs.match(/[0-9.\s]+/ig);
                    output = output[0] || false;
                } else {
                    output = data.match(/[0-9.\s]+/ig);
                    output = output[1] || false;
                }
                output = (output !== false) ? Number(output.replace(/\s/,'')) : output;
                callback(output);
            },
            error: function() {
                callback(false);
            }
        });
    }

    function output(data) {
        alert( data );
        $('#show_product_price_api').val(data);   
    }

but when i use this function :

forex(100, 'USD', 'EUR', output);

to fire the event, i get a "FALSE" callback

any idea why this error function is called ??


UPDATE 2

i think it's a cross domain issue, does anyone have any sugestions using jsonp ?

Upvotes: 0

Views: 2698

Answers (1)

Garfield
Garfield

Reputation: 2537

Code is fine. Take a look at the http://www.google.com/ig/calculator?hl=de&q=1USD=?EUR's response.

It is not a valid JSON string. so it will not go into the done.

Response is {lhs: "1 US-Dollar",rhs: "0,767165324 Euro",error: "",icc: true} It should be {"lhs": "1 US-Dollar","rhs": "0,767165324 Euro","error": "","icc": true}.

Edited:

$.ajax({
    url: "http://www.google.com/ig/calculator?hl=de&q=1USD=?EUR"
}).done( function ( data ) {
    data = data.replace(/([a-z0-9]+):/gi,"\"$1\":"));
    var obj = $.parseJSON( data )
    alert( data.rhs );
});

Upvotes: 1

Related Questions