Bitcoin Forum
December 04, 2016, 08:29:47 AM *
News: Latest stable version of Bitcoin Core: 0.13.1  [Torrent].
 
   Home   Help Search Donate Login Register  
Pages: [1]
  Print  
Author Topic: Javascript problem with Cryptoxchange API (cross-domain request) - RESOLVED.  (Read 4607 times)
twa
Full Member
***
Offline Offline

Activity: 139


View Profile
March 05, 2012, 03:45:34 AM
 #1

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:

<?php
$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!



Pages: [1]
  Print  
 
Jump to:  

Sponsored by , a Bitcoin-accepting VPN.
Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!