Home > Software engineering >  How to pull data from a complicated API using AJAX and display on a .php page
How to pull data from a complicated API using AJAX and display on a .php page

Time:03-17

Right now, the website I'm helping with is purely php, html, css, and some javascript.

I use the php to pull the data off of the Web-API and post it to the webpage.

e.g.:

$pool = json_decode(file_get_contents("http://api.link:port/api/v1/Pool-Avian/"), false); 
//Removed API link since I don't have the owner's permission for specifics at this time.
        <table >
            <tbody>
                <tr>
                    <th>Block Reward:</th>
                    <td id="lastBlockReward">~2475 AVN</td>
                </tr>
                <tr>
                    <th>Blockchain Height:</th>
                    <td>     
                        <?php echo $pool->body->primary->network->height; ?>
                    </td>
                </tr>
                <tr>
                    <th>Network Hashrate</th>
                    <td>
                        <?php echo hashRateCalculator($pool->body->primary->network->hashrate); ?>
                    </td>
                </tr>
                <tr>
                    <th>Network Difficulty</th>
                    <td>
                        <?php echo hashRateCalculator($pool->body->primary->network->difficulty); ?>
                    </td>
                </tr>
                <tr>
                    <th>Blocks Found By Pool</th>
                    <td>
                        <?php echo $pool->body->primary->blocks->valid; ?>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

The API is like this:

{"version":"0.0.3","statusCode":200,"headers":{"Access-Control-Allow-Headers":"Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Allow-Methods","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Content-Type":"application/json"},"body":{"primary":{"config":{"coin":"Avian","symbol":"AVN","algorithm":"x16rt","paymentInterval":21600,"minPayment":0.01,"recipientFee":0.01},"blocks":{"valid":83,"invalid":0},"shares":{"valid":20734,"stale":124,"invalid":0},"hashrate":{"shared":68131817.9050706,"solo":0},"network":{"difficulty":738.1659173695874,"hashrate":116186636292.9936,"height":541555},"payments":{"last":1647460164235,"next":1647460254235,"total":198724.56746191},"status":{"effort":61.25198558663565,"luck":{"luck1":7.93,"luck10":64.47,"luck100":89.27},"miners":3,"workers":3}},"auxiliary":{"config":{"coin":"","symbol":"","algorithm":"","paymentInterval":0,"minPayment":0,"recipientFee":0},"blocks":{"valid":0,"invalid":0},"shares":{"valid":0,"stale":0,"invalid":0},"hashrate":{"shared":0,"solo":0},"network":{"difficulty":0,"hashrate":0,"height":0},"payments":{"last":0,"next":0,"total":0},"status":{"effort":0,"luck":{"luck1":0,"luck10":0,"luck100":0},"miners":0,"workers":0}}}}

I reviewed some websites and tutorials for how to do this, but I can't seem to get them to work...

Right now, my test page has this:

<script>
            miner = 0;
            function updateData() { //Obtain data from API and push to website//
                miner = miner   1;
                document.getElementById("minerBottom").innerHTML = miner;
            }
            window.onload = function () {
                webHandler();
            };
            
            function webHandler() {
                const xhr = new XMLHttpRequest();
                xhr.open("GET", "http://api.link:port/api/v1/Pool-Avian/", true); 
                //again - API redacted//
                xhr.onload = function () {
                    if (this.status === 200) {

                        // Changing string data into JSON Object
                        obj = JSON.parse(this.responseText);

                        // Getting the ul element
                        let list = document.getElementById("list");
                        str = "";
                        for (key in obj.data) {
                            str  =
                                    `<li>${obj.data[key].employee_name}</li>`;
                        }
                        list.innerHTML = str;
                    } else {
                        console.log("File not found");
                    }
                };
                xhr.send();
            }
        </script>

and the test elements are:

<div >
    <div  id="minerTop">
        Miners
    </div>
    <div  id="minerBottom">

    </div>
</div>
<div >
    <div  id="workerTop">
        Workers
    </div>
    <div  id="workerBottom">
        0
    </div>
</div>
<div >
    <div  id="blockTop">
        Blocks
    </div>
    <div  id="blockBottom">
        0
    </div>
</div>

It's losing me at the "Getting the ul element" part - I'm not sure what it's trying to do, or how I'd morph this into what I need it to do.

What I want it to do is find the pair I'm looking for (e.g. body->primary->status->miners) and display it in the appropriate <div>

Based on answer - updated script to:

function webHandler() {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", "http://api.link:port/api/v1/Pool-Avian/", true);
    //again - API redacted//
    xhr.onload = function () {
        if (this.status === 200) {
            // Changing string data into JSON Object
            obj = JSON.parse(this.responseText);

            // get "miners" from API response. 
            // This does not validate if the value is actually in the object!
            let miners = obj.body.primary.status.miners;
            // get DOM element by id
            let minersElement = document.getElementById('minerBottom');
            // set value of miners as text in DOM
            minersElement.innerText = miners;

        } else {
            } else {
        console.log("File not found");
    }
        }
    };
    xhr.send();
}

No display in those div are happening

CodePudding user response:

For miners, here's an example in your test page script.

if (this.status === 200) {
    // Changing string data into JSON Object
    obj = JSON.parse(this.responseText);

    // get "miners" from API response. 
    // This does not validate if the value is actually in the object!
    let miners = obj.body.primary.status.miners;
    // get DOM element by id
    let minersElement = document.getElementById('minerBottom');
    // set value of miners as text in DOM
    minersElement.innerText = miners;
    
} else {
    console.log("File not found");
}
                

Please note, that this does not include any sanitizing checks or validation if response from API is valid.

  • Related