1

I am trying to get some data from this api:

https://www.bitstamp.net/api/ticker/

into a jquery variable (to eventually display on a web page). It returns a JSON dictionary (more information here https://www.bitstamp.net/api/).

I tried for hours on end doing it all client side but realised that I cant because the api doesn't support cross-origin requests nor JSONP. So I then moved onto serverside code:

I have a php file 'test.php' with the following code:

<?php
$homepage = file_get_contents('https://www.bitstamp.net/api/ticker/');
echo $homepage;
?>

Then inside my html page I have the following code:

<script>
var last = JSON.parse(test.php)["last"]
document.getElementById('apidata').innerHTML=last;
</script>
<span id="apidata"></span>

But I don't know why it's not working! Can anyone please shed some light on this?

I thought jquery may be simpler but if anyone knows how to get this done with JS I'd like to hear that too. I also suspect that my php file is wrong.

EDIT: Here's a link to my php file http://www.buyabitcoin.co.uk/beta/test/test.php and my html file http://www.buyabitcoin.co.uk/beta/test/test.html

username: 'test' password: 'test123'

EDIT: I have also tried

$.getJSON('test.php', function(response) {$("#apidata").html(response.value); });

in the html but to no avail. Can anyoneplease confirm if my php is outputting a JSON rather than a string?

Many thanks in advance

2
  • sidenote: JSON.parse(test.php) The parse function will look for an object test and its node php. You forgot the quotation marks. If you're on jquery, give this a try: $.getJSON('test.php', function(response) { /* do this and that with the response */ });` Commented Apr 23, 2013 at 7:55
  • @Imperative Thanks. Using your code, how do I turn one of the numbers from the JSON into a variable? Regards. Commented Apr 25, 2013 at 2:28

4 Answers 4

1

Modify your php file like so:

<?php
header('Content-type: application/json');
$homepage = file_get_contents('https://www.bitstamp.net/api/ticker/');
echo $homepage;
?>

The header() tells the requesting entity what sort of data it provides. The url you request (https://www.bitstamp.net/api/ticker/) provides this json string:

{
    "high": "161.00",
    "last": "154.00",
    "bid": "153.51",
    "volume": "20295.34112055",
    "low": "135.10",
    "ask": "154.00"
}

Your html page has this JQuery:

$.getJSON('test.php', function(response) {
    // access the response here
    // e.g. get the volume
    var volume = parseInt(response.volume);
    // the numbers are returned as strings (numbers in quotes), thats why parseInt should be used
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I've solved my problem. I tried your suggested method anyway but I'm afraid I can't get it to work! Thanks anyway.
1

You can use jQuery ajax function to get JSON from the php page

like,

$.ajax({
    dataType: "json",
    url: 'test.php',
    data: data,
    success: function(data){
        var last = data.last
        $('#apidata').innerHTML=last;
    }
});

Read more about jQuery.ajax http://api.jquery.com/jQuery.ajax/

6 Comments

Many thanks. I've tried it but it doesn't seem to work. Do I need to modify the code or just copy it as is? Could my php be outputting a string rather than a json?
Your php page should return a json not a string. You can check if in firebug that your php page is returning a json or string. What content you get in php page? If you give some content then it will be more useful to solve your problem.
You can see my php here: buyabitcoin.co.uk/beta/test.php (username: 'test' password: 'test123') My php page gives the same content as when you type the api's address into the browser. So if you go to bitstamp.net/api/ticker in your web browser, that's what I see when I go to my php page.
I am not sure if this is intentional or not, but your test.php seems to be outputting HTML around the JSON data. This should not happen. Additionally, try making sure that the correct header is outputted. The MIME media type for JSON text is application/json. header("Content-Type: application/json");
@timgws No it wasn't intentional. I've now made the tesp.php page just php. How can I ensure I am the outputting the correct header? Many thanks in advance
|
0

You do not need to have jQuery just to download a JSON string and replace a div's content!

function loadXMLDoc() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            r = JSON.parse(xmlhttp.responseText);
            document.getElementById("apidata").innerHTML=r;
        }
    }

    xmlhttp.open("GET","/beta/test/test.php",true);
    xmlhttp.send();
}

loadXMLDoc();

Comments

0

I managed to do what I want with the following code. This allows me to 'extract' a value from the JSON (in this example, the value for 'last') to use as a JS variable in a separate html file:

In my php file:

<?php
$ticker = file_get_contents('https://www.bitstamp.net/api/ticker/');   
$obj = json_decode($ticker,true); // Split the JSON into arrays.
echo json_encode(array("myVariable" => $obj['last']));
?>

In my html file:

$.getJSON('test.php', function(data) {
var myVar = data.myVariable }); 

I hope this helps someone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.