Skip to content Skip to sidebar Skip to footer

Json Data Through Js/ajax Into Php

Goal: I'm using the coinmarketcap.com API (link). Beforehand I got their data into PHP. Sample:

Solution 1:

Writing data back to PHP is not possible afaik because PHP is evaluated on serverside and the client just gets its resulting page. But here is a solution with JavaScript, which is only running on the client side:

As you should know your result looks something like this:

[
{
    "id": "bitcoin", 
    "name": "Bitcoin", 
    "symbol": "BTC", 
    "rank": "1", 
    "price_usd": "17391.5", 
    "price_btc": "1.0", 
    "24h_volume_usd": "15047800000.0", 
    "market_cap_usd": "291076752838", 
    "available_supply": "16736725.0", 
    "total_supply": "16736725.0", 
    "max_supply": "21000000.0", 
    "percent_change_1h": "-0.14", 
    "percent_change_24h": "3.75", 
    "percent_change_7d": "45.85", 
    "last_updated": "1513104255", 
    "price_eur": "14834.288623", 
    "24h_volume_eur": "12835201583.6", 
    "market_cap_eur": "248277409254"
}, 
....
]

It's an Array of objects where each object contains the following properties (id, name, symbol, ... , market_cap_eur).

To display all those you would need to loop through the array and create some kind of dispalytemplate for the objects.

Therefore you should replace the following line of code in the registered onreadystatechange-function:

document.getElementById("collect").innerHTML = obj;

with something like:

var objlength = obj.length;
var element = document.getElementById("collect");
element.innerHTML = "";
for ( var i = 0; i < objlength; i++){
    element.innerHTML += JSON.stringify(obj[i])+"<br />";
}

This would create a stringified result for each cryptocurrency in a new line. The result of it will still be unreadable and the code to setup the innerHTML is really dirty. To enhance atleast the display even more, you could do something like:

var objlength = obj.length;
var element = document.getElementById("collect");
element.innerHTML = "";
for ( var i = 0; i < objlength; i++){
    element.innerHTML += obj[i].name+" is "+ obj[i].price_eur +"<br />";
}

which should return the name of the curreny and the current EUR price per line. You can extend this by all desired properties.

But as mentioned it's quick and dirty and please don't judge me by this code.

Also you need to delete the + Math.Random() in you request. Here is a working live example: http://plnkr.co/edit/aHXFVAjH6qoKk2vmOf0u?p=preview

Solution 2:

PHP CODE

<?php$url = "https://api.coinmarketcap.com/v1/ticker/?convert=EUR";
$response = file_get_contents($url);
echo$response;
?>

Because the URL returns JSON data, already

Post a Comment for "Json Data Through Js/ajax Into Php"