Search code examples
jquerygetjson

JQuery.getJSON - 'Access-Control-Allow-Origin'


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

});

Solution

  • 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