Get JSON from remote domain using jQuery when CORS not possible

The same origin policy means you cannot get data from a different server unless it allows cross-origin resource sharing (CORS).

To get round this restriction we can use the JSONP function of jQuery, however we do need to wrap the returning data in a javascript function specified by the initial request.

The 2 basic bits of code required are…

JQUERY:

$.ajax(
    {
        url: 'http://www.someotherdomain.com/json-feed.php',
        dataType: 'jsonp',
        success: function( data ){
        console.log( data ) ;
    }
});

PHP:

echo $_GET['callback'] . '(' .$aaMyJSONData . ');' ;

If the server allows CORS, you can send back the required headers using the following code:

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400'); // cache for 1 day
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>