javascript - Can not get data from AJAX request to the Coinhive API

819

I recently tried to get the data from a Json API and post that back to a table in html. I tried to do this from:https://api.coinhive.com/user/balance?name=username&secret=mysecret It does show me:{"success":true,"name":"*user*","total":49152,"withdrawn":0,"balance":* a value *}

But I want to let my users push a button which will load the balance value to a table in their own user portal.

I got the user portal setup with all the mysqlvalues, But i can't manage to get the jsonpart to work.

Can anyone please help me?

Thanks in common, Dennis.

edit:

I tried the following:

<html lang="en">
<head>
<title>JavaScript - read JSON from URL</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>

<body>
    <div class="mypanel"></div>

    <script>
    $.getJSON('https://api.coinhive.com/user/balance?name=username&secret=mysecret', function(data) {

        var text = `Balance: ${data.balance}<br>`


        $(".mypanel").html(text);
    });
    </script>

</body>
</html>

And I also tried:

function setup() {
    loadJSON("https://api.coinhive.com/user/balance?name=username&secret=mysecret", gotData);
}

function gotData(data) {
    alert(data);
}

And that isn't working. What am I doing wrong?

454

Answer

Solution:

figured it out!

The JSON request:

<?php
$url = 'the api url';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  "Content-Type: application/x-www-form-urlencoded"
));

$data = curl_exec($ch);
curl_close($ch);

$result = json_decode($data, true);

?>

The postback to the end user:

<span id="test" class="page_speed_1728654869"><?php
if (isset($data))
{
   echo $result['balance'];
}
else
{
   echo 'damn';
}
?></span>

I decided to go with php and kind of ditch the html getjson part.

29

Answer

Solution:

Client side requests to the Coinhive HTTP API are restricted by CORS rules:

From API documentation:

You should never call the Coinhive HTTP API from the client side.

People are also looking for solutions to the problem: php - If username is set and password is not, display me an error message

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.