Bitcoin Forum
May 26, 2024, 03:57:52 AM *
News: Latest Bitcoin Core release: 27.0 [Torrent]
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: Javascript problem with Cryptoxchange API (cross-domain request) - RESOLVED.  (Read 4799 times)
twa (OP)
Full Member
***
Offline Offline

Activity: 320
Merit: 100


BitSong is a decentralized music streaming platfor


View Profile
March 05, 2012, 03:45:34 AM
Last edit: March 05, 2012, 06:04:43 AM by twa
 #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:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!