Bitcoin Forum

Bitcoin => Project Development => Topic started by: BitTalkyy on October 18, 2015, 05:53:01 PM



Title: Get the current bitcoin price and the balance of an address in PHP and jQuery.
Post by: BitTalkyy on October 18, 2015, 05:53:01 PM
Hi guys! Before we begin, I would say that I will use Blockchain.info here.
Let's begin with the price calculator. It's very simple.

First, create a completely new php file called 'get.php'.
In that file, start your PHP tags normally.

Then create a variable like so:
Code:
$json_response = file_get_contents('http://www.blockchain.info/ticker');
After that, echo it like this:
Code:
echo $json_response;
We will bemaking an Ajax request to this page instead Blockchain.info, because we can only Ajax in our domain.

So here's the code for 'get.php'
Code:
<?php
$json_response 
file_get_contents('http://www.blockchain.info/ticker');
echo 
$json_response;
?>


In your main file's <head> section, include the latest jQuery build.

At the bottom of your <body> tag, open a <script> tag.
In it, write:
Code:
$.ajax({
    url : "get.php",
    success : function(result){
       var price = result.USD.last;
    }
});

At this point, the price variable contains the price in USD.

Then you can use the innerHTML variable of elements to display it.

Next, the balance of an address. This is easy too.
We will use the same trick as before, but with some changes.

Create a new PHP file called 'balance.php'.
Inside it, write:
Code:
$address = //address you want to get
$json_response = file_get_contents('http://www.blockchain.info/address/'.$address.'/?format=json');
echo $json_response;

In your main file, include jQuery as before and create the script tag at the end of the script.
I will use 'final_balance', but you can use 'total_received'. Take a look at the 'Single Address' section here: https://blockchain.info/api/blockchain_api
In that script tag, write:
Code:
$.ajax({
    url : "balance.php",
    success : function(result){
         var balance = result.final_balance / 100000000;
    }
});
As you can see, we're dividing it by 100000000, because the API gives the balance in satoshi. If you run a faucet, you may not want to convert it.
Then, you can use the same innerHTML variable of any element on your page to display it.

I hope you learnt something! I'll be posting more tutorials soon! if you have programming work for me, I can do it for cheap prices! Contact me via PM.

Tips are appreciated: 1Tipo4u5vkaNDjPd5A4wxPxmR4bEp8Bdb