Cross-Origin Request Blocked on

Look at Same Origin Policy. Regarding

This can be fixed by moving the resource to the same domain or
enabling CORS

and the fact you are using WordPress, you can create a proxy very easy like this :

proxy.php :

<?
header('Content-type: application/json');
$url=$_GET['url'];
$json=file_get_contents($url);
echo $json;
?>

Then you want to call a resource outside the domain, as with AJAX, use proxy.php to fake that you are trying access the resource from the same domain. Like :

var url= "my-external-resource.com?param=value";
url="proxy.php?url="+url:
$.ajax({
    url: url,
    dataType: 'json',
    success:  function (data) {
        ...
    }
});

Here the result is expected to be JSON, but just change header / datatype to HTML, XML or whatever if needed.


Update : @Jason raises an interesting point about security. I totally agree. Under normal circumstances one could prevent remote access to files by .htaccess and a <Files> directive :

<Files proxy.php>
    Order Deny,Allow
    Deny from All
    Allow from 127.0.0.1
</Files>

…but this is not satisfactory, since it will prevent using proxy.php in AJAX calls as well. A solution is to check if proxy.php is called by another script :

if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('HTTP/1.0 403 Forbidden');
    die('You are not allowed to access this file.');     
}

This will allow using proxy.php in javascript AJAX calls, but prevent direct access from remote (or locally). See this answer for more about $_SERVER['HTTP_X_REQUESTED_WITH'] and XMLHttpRequest.

Leave a Comment