MrSnrub
MrSnrub

Reputation: 455

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);

});

Upvotes: 1

Views: 84

Answers (2)

Abiodun
Abiodun

Reputation: 467

This works if you run the your server without using https. Note fetchApi was used instead of jquery Library as its not readily available in the browser

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


function fetchData(url) {
      return fetch(url, {
          method: 'get'
      }).then(function(response) {
          return response.json();
      }).catch(function(err) {
          console.log(error);
      });
  }
 fetchData(tsp_api).then((data)=> console.log(data)).catch((err)=> console.log(err));

This won't work on jsfiddle using HTTPS, the browser will refuse to load any resources over HTTP. As you've tried, changing the API URL to have HTTPS instead of HTTP typically resolves this issue. However, your ebrent.net did not allow CoRS for HTTPS connections. Because of this, you won't be able to get your result for jsfiddle

Upvotes: 0

Pedro Lobito
Pedro Lobito

Reputation: 98881

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);
});

Upvotes: 1

Related Questions