MrSnrub MrSnrub - 6 months ago 23
PHP Question

Cannot call getJSON method to fetch data

I am trying to fetch some JSON data. I can access the data just fine in a regular web browser, like this: http://www.ebrent.net/apis/tsp.php?fund=G+Fund&start=2003-01-01&end=2004-01-01, but I cannot get it to work in jQuery. What am I doing wrong?

Please take a look at my jsFiddle: https://jsfiddle.net/MrSnrub/mq31hwuj/

var tsp_api = '//www.ebrent.net/apis/tsp.php?start=2003-01-01&end=2004-01-01';

$.getJSON( tsp_api, function(json) {

// This alert never gets called.
alert("Success!");

// Set the variables from the results array
var data = json;
// console.log('Data : ', data);

// Set the div's text
$('#div-data').text(data);

});

Answer

You cannot get the result because the remote site doesn't have CORS enabled: If you look at the console, you'll see:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://www.ebrent.net/apis/tsp.php?start=2003-01-01&end=2004-01-01. (Reason: CORS header 'Access-Control-Allow-Origin' missing).


You can bypass CORS by using something like anyorigin.com, i.e.:

$.getJSON('http://anyorigin.com/get/?url=http%3A//www.ebrent.net/apis/tsp.php%3Fstart%3D2003-01-01%26end%3D2004-01-01&callback=?', function(data){
    $('#div-data').html(data.contents);
});
Comments