0

I'm trying to retrieve data from a web API in JSON. And I'm getting the "No 'Access-Control-Allow-Origin' header is present on the requested resource." error, I understand why I'm getting this, but don't know what I need to do next in order to allow me to get the data from the different domain. I have recently and very quickly learnt about JSONP and stuff, but Im having a hard time understanding what I need to do.

$(document).ready(function() {

$.getJSON('http://www.thewebsite.net/json',
 function(value) { 

    document.write(value.id); 
});

});
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Hopeless
  • 375
  • 1
  • 4
  • 17
  • 1
    A standard JSON request is restricted by the same-domain policy, meaning a script running on domain A cannot access data on domain B. Does the API you're calling mention supporting JSONP specifically (with a callback parameter)? If you're unsure, try loading `http://www.thewebsite.net/json?callback=foo` in your browser and see if the output starts with `foo`. If so, then JSONP is supported and you can do something like http://learn.jquery.com/ajax/working-with-jsonp/ to access the data. – Graham Dec 01 '13 at 18:01
  • don't use `document.write` after page is loaded...will wipe out everything in page. Best practice to only use it in special circumstances – charlietfl Dec 01 '13 at 18:03
  • @Graham Ive tried the jsonp method, dont think the website supports it. – Hopeless Dec 01 '13 at 18:59
  • Check out the answer at http://stackoverflow.com/questions/8537601/is-there-a-free-json-proxy-server-which-supports-cors-or-jsonp ; this is using YQL to access the JSON at a cross-domain URL, and then wrapping it in a callback. – Graham Dec 01 '13 at 21:21
  • I have read about YQL before and I think I get the concept, but I've gone with creating a PHP Proxy, I'm going to look in YQL in the future but ive been banging my head against a brick wall for a couple of days with this so for now. thanks for the suggestions – Hopeless Dec 02 '13 at 02:37

1 Answers1

2

Ok so if you know about the same origin policy, you know that by default a browser can only make request to the same host. One way would be to call a server side script on your server (PHP), and that PHP fetches the remote JSON, and returns the data to your javascript. Search for JSONP and CORS for alternative solutions.

JS:

$(document).ready(function () {
    $.getJSON(
        '/proxy.php',
        {
            id: 5
        },
        function (response) {
            var data = response.data;
            // do something with data
        }
    );
});

proxy.php:

    $id = (integer) $_GET['id'];
    $response = file_get_contents('www.some-remote-site.com/api/id=' . $id);

    return $response
bagonyi
  • 3,258
  • 2
  • 22
  • 20