Author

Topic: Javascript problem with Cryptoxchange API (cross-domain request) - RESOLVED. (Read 4813 times)

twa
full member
Activity: 320
Merit: 100
BitSong is a decentralized music streaming platfor
I am trying to use some simple javascript to poll the ticker at Cryptoxchange.com.

Code:

$.getJSON("http://cryptoxchange.com/api/v0/data/BTCUSD/ticker", function(data) {
       console.log(data);
 });


Now, the response that I get is:

XMLHttpRequest cannot load http://cryptoxchange.com/api/v0/data/BTCUSD/ticker. Origin http://mysite.com is not allowed by Access-Control-Allow-Origin.

Solution

This problem is related to an issue with Javascript and cross-domain security.  You can't make cross-server http requests with Javascript as this is blocked 99% of the time.  

The solution to this problem is simple.

Create "proxy.php" that contains the following:

$url = 'http://cryptoxchange.com/api/v0/data/BTCUSD/ticker';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo json_encode($output);
?>


So what happens is obvious.  You go to http://yoursite.com/proxy.php and you get the JSON response from the php script.

Now in your main html file, you just use http://yoursite.com/proxy.php as the address for the Javascript HTTP request.

$.getJSON("proxy.php", function(data) {
     console.log(data);
});


Its that simple!



Jump to: