san45
san45

Reputation: 459

error in parsing json

The below is the code to parse a json file recieved from an api. But after parsing it doesn't show any output,

var codingAPI = "http://glosbe.com/gapi/translate from=eng&dest=hin&format=json&phrase=boy";

$.getJSON(codingAPI, function (json) {

    // Set the variables from the results array
    var address = json.tuc[0].pharse.language;

    $('#address').text(address);

});

// Caching the link jquery object
var $myLink = $('a.myLink');

// Set the links properties
$myLink.prop({
    href: codingAPI,
    title: 'Click on this link to open in a new window.'
}).click(function (e) {
    e.preventDefault();
    window.open(this.href, '_blank');
});

the code is placed in jsfiddle

Upvotes: 0

Views: 118

Answers (2)

Qantas 94 Heavy
Qantas 94 Heavy

Reputation: 16020

As cross-origin requests have not been permitted to this file, you can use JSONP -- it's supported by the server. With jQuery, you can just use ?callback=? to make the response succeed.

var codingAPI = "http://glosbe.com/gapi/translate?from=eng&dest=hin&format=json&phrase=boy&callback=?";

$.getJSON(codingAPI, function (json) {

    // Set the variables from the results array
    var address = json.tuc[0].phrase.language;

    $('#address').text(address);

});

// Caching the link jquery object
var $myLink = $('a.myLink');

// Set the links properties
$myLink.prop({
    href: codingAPI,
    title: 'Click on this link to open in a new window.'
}).click(function (e) {
    e.preventDefault();
    window.open(this.href, '_blank');
});

Also, you've misspelt phrase as pharse in your callback function.

Upvotes: 1

Alex
Alex

Reputation: 4774

It's due to the same origin policy.

See the console error

XMLHttpRequest cannot load http://glosbe.com/gapi/translate?from=eng&dest=hin&format=json&phrase=boy. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.

Upvotes: 3

Related Questions