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

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?

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" style="color:white"><?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.

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.

Related

Need to call SAP web service to send XML file from web page using JavaScript

We need to call an SAP web service from our website and submit an XML file to the SAP url. SAP API has credentials.
The purpose is to execute a function module in SAP which creates an SAP user ID and then returns the SAP user ID name back to our website via a return xml.
Below is the PHP code which i have tried.
<?php
$credentials = "Username:Password";
// Read the XML to send to the Web Service
$request_file = "m2bsubscr.XML";
$fh = fopen($request_file, 'r');
$xml_data = fread($fh, filesize($request_file));
fclose($fh);
$url = "SAP API HERE";
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: \"run\"",
"Content-length: ".strlen($xml_data),
"Authorization: Basic " . base64_encode($credentials)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
// Apply the XML to our curl call
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
$data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
} else {
// Show me the result
echo "Success!<br />\n";
}
curl_close($ch);
// Handle the response from a successful request
$xmlobj = simplexml_load_string($data);
var_dump($xmlobj);
?>
My XML File:
<n0:_-majul_-m2bSubscriptionCreate xmlns:n0="urn:sap-com:document:sap:soap:functions:mc-style">
<IsSubscription>
<Bupar></Bupar>
<Sstat></Sstat>
<Categ></Categ>
<Fname>Wolfgang</Fname>
<Lname>Haerle</Lname>
<Email>whaerle#hotmail.com</Email>
<Srmrk></Srmrk>
<Cczip></Cczip>
<Cccty></Cccty>
<Ccadr></Ccadr>
<Cntry>US</Cntry>
<Product>1</Product>
<Begda>2020-07-08</Begda>
<Endda>2020-08-08</Endda>
<Price>765</Price>
<Curr>USD</Curr>
<Quantity>1</Quantity>
<Unit>MON</Unit>
<Userid></Userid>
</IsSubscription>
</n0:_-majul_-m2bSubscriptionCreate>
but it returns Success with bool(false) as a result. I tried to display error but it has no error.
Please help me to find what is the issue.
I wanted to do this in JavaScript. Kindly suggest me the way to do.

reCAPTCHA V2 Failing On Server Side Validation

My reCaptcha V2 "I'm not a robot" is failing on the server side.
It seems to be failing at:
post_captcha($_POST['g-recaptcha-response'])
Both the public & pvt key are correct and on the correct domain.
It's been 3 hours since I've created the reCAPTCHA so maybe it takes a while to process my domain through the system? I'm not sure....
Here is the HTML:
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="contact-form.php" method="POST">
<div class="g-recaptcha" data-sitekey="PUBLIC KEY"></div>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
Here is the PHP:
<?php
// Checks if form has been submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => 'PVT KEY',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the CAPTCHA wasn't checked
echo '<p>Please go back and make sure you check the security CAPTCHA box.</p><br>';
} else {
echo 'success';
}
}
?>
Any help will be greatly appreciated!
Thank you.
Long time no answer. The issue was because of my web service provider having limitations on the shared server I was subscribe to e.g. not being able to edit php.ini config file.
Solution: don't use a shared server!

Hide Elements based on Data atributte JQuery

I'm trying to write a basic PHP script that will fetch my own Instagram photos and only display the ones I want based on the hashtags I've added to them.
So far based on some tutorials and my self-taught PHP and JS I came up with this:
<html>
<head>
<script src="assets/js/jquery.min.js"></script>
</head>
<?php
<html>
<head>
<script src="assets/js/jquery.min.js"></script>
</head>
<?php
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
function fetchData($url){
function fetchData($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$result = fetchData("https://api.instagram.com/v1/users/1013397/media/recent/?access_token=1013397.ab103e5.5061b21c8fb0436bb20d881d46f9ae5c&count=14");
$result = json_decode($result);
foreach ($result->data as $post) {
if(empty($post->caption->text)) {
// Do Nothing
}
else {
echo '
<div data-tag="'.$post->caption->text.'">
<a class="instagram-unit" target="blank" href="'.$post->link.'">
<img data-tag="'.$post->caption->text.'" class="gallery-item" src="'.$post->images->standard_resolution->url.'" alt="'.$post->caption->text.'" width="100%" height="auto" />
</a>
</div>';
}
}
?>
<script>
$(document).ready(function(){
var permit = '#aruba'
$('div').each(function(){
if($('div').attr('data-tag').indexOf(permit) > -1 ){
console.log('has tag')
}
});
});
</script>
I'm trying to hide all the images that don't have the hashtag writen in the JS bar. But so far no luck.
What am I doing wrong?
$(document).ready(function(){
//find all divs, filter out any who do have the matching tag, hide all that don't
$('div').filter(function(){ return $(this).data('tag') !== "#aruba"; }).hide();
});
Talking about your original issue, part of your issue is your doing an each() over the divs, but then inside there your looking them all up again so you lost context of which one you were actually evaluating which could have been accessed with 'this' or '$(this)'.
Also when working with data elements, use data() and leave off the 'data-' part of the key.

Read feed on a Facebook page without login in

Is it possible to create a web site and, with JavaScript, read the feed from a Facebook page and display it to my sites visitor without them having to login, or even have Facebook for that matter.
I'm getting lost in the Facebook documentations :(
Thanks to #mch here commes version that uses php as a proxy to read a Facebook feed with JavaScript.
Place a file called proxy.php on your server and add this code:
<?php
// always add this header to ensure the JSON is output in the correct format
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header('Content-Type: application/json; charset=utf-8');
$graphUrl = $_POST[graphUrl];
if ($graphUrl == "") {
$graphUrl = "https://graph.facebook.com/facebook/feed/";
}
//App Info, needed for Auth
$app_id = "1234567890";
$app_secret = "0000011122234334445556aaass";
//retrieve auth token
$authToken = fetchUrl("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={$app_id}&client_secret={$app_secret}");
//Echo back json to read client side.
echo fetchUrl("{$graphUrl}?{$authToken}");
function fetchUrl($url){
$ch = curl_init();
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$retData = curl_exec($ch);
curl_close($ch);
return $retData;
}
?>
Change app_id, app_secret to your apps ids. Create apps here https://developers.facebook.com/apps/
Create a HTML file next to your proxyfile. Add this code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>FB reader</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var timeout = 5000,
load_error;
load_error = function (jqXHR, textStatus, errorThrown) {
if (errorThrown === "timeout") {
alert('Server bussy');
} else {
alert('error: 404', textStatus + ": " + errorThrown);
}
};
$(document).ready(function() {
console.log('Loading from Facebook...\n');
//Change data: {graphUrl: 'https://graph.facebook.com/iambounty/feed'}, to what ever you want.
$.ajax({
type: 'POST',
url: 'proxy.php',
data: {graphUrl: 'https://graph.facebook.com/iambounty/feed'},
timeout: timeout,
error: load_error,
success: function (rv) {
var data = rv.data,
len = data.length,
i,
out = '';
for (i = 0; i < len; i += 1) {
if (data[i].description) {
out += data[i].description + '\n\n';
}
}
console.log(out);
}
});
});
});
</script>
</body>
</html>
You can do it on the server side with PHP. Create a facebook App in the Facebook developer center to get a App Key and Secret Key.
$profile_id = "1234567890";
//App Info, needed for Auth
$app_id = "0001234567890";
$app_secret = "abc123ebf123f3g5g6j";
/* USE THIS LINE INSTEAD OF THE "veryfypeer" LINE BELOW */
Facebook::$CURL_OPTS[CURLOPT_CAINFO] = '/path/to/crt/fb_ca_chain_bundle.crt';
//retrieve auth token
$authToken = fetchUrl("https://graph.facebook.com/oauth/access_token?type=client_cred&client_id={$app_id}&client_secret={$app_secret}");
$data['feed_data'] = fetchUrl("https://graph.facebook.com/{$profile_id}/feed?{$authToken}");
function fetchUrl($url){
$ch = curl_init();
/* DO NOT USE THE FOLLOWING LINE: I'VE COMMENTED IT OUT HERE */
// curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
$retData = curl_exec($ch);
curl_close($ch);
return $retData;
}
... on the Javascript side I think it's not possible, since the FB API Secret must be hidden from the public. Information taken from here

Javascript to make Post or Get call to a URL and return the text that's on the page

I've been trying to do this all morning I need to make either a POST or a GET call to this
URL http://cabbagetexter.com/send.php
I need it to return the text that's on the page, I know it can't be that difficult but I'm completely code blocked on this one,
I've tried using JQuerys .post and .get functions but I cant seem to return just the text on the page
any help would be appriciated
EDIT:
Ah ok so there's a technical reason for not being able to do it. balls, Thanks for the help guys
(function ($) {
$.ajax({
url: 'http://cabbagetexter.com/send.php',
type: 'text',
success: function (response) {
//do something with the text from the site
}
});
}(jQuery));
Obviously you need to host this script on the URL you are loading because of the same origin policy
You are running into the cross domain limitation. You can only to a request to a page in the same domain.
There is another possibility if you need to post calls to a page on another domain. Let's say your Javascript is being run from index.php. You might create a file called ctexter.php.
ctexter.php would use curl to make the post request to http://cabbagetexter.com/send.php, and would then output the response (the output from) send.php. So, if index.php makes an ajax call to ctexter.php, and ctexter.php is outputting the response from send.php, you have in effect achieved your goal.
You could make the curl post requests with this function:
function post_request($url, $data) {
$output = array();
foreach ($data as $key => $value) {
if(is_object($value) || is_array($value)){
$data[$key] = serialize($value);
}
}
$output = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
if ($result) {
$output['status'] = "ok";
$output['content'] = $result;
} else {
$output['status'] = "failure";
$output['error'] = curl_error($ch);
}
curl_close($ch);
return $output;
}
where $url is (obviously) the url to post to, and $data is an associative array containing the data you want to submit.
Then on ctexter.php you could do something like:
// Since we already built the post array in the
// ajax call, we'll just pass it right through
$response = post_request("http://cabbagetexter.com/send.php", $_POST);
if($response['status'] == "ok"){
echo $response['content'];
}
else{
echo "It didn't work";
}
Finally, hit ctexter.php using JQuery .post():
$.post("ctexter.php",
{
firstparamname: "firstparamvalue",
somethingelse: "llama"
},
function(data) {
alert("It worked! Data Loaded: " + data);
});
If you're on the same domain, you'd use some code like this:
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200)
{
document.getElementById("targetElementID").textContent = ajax.responseText;
}
}
ajax.open("GET","http://cabbagetexter.com/send.php",true);
ajax.send();
Learn how to use AJAX
If not, then, sorry, you're out of luck because you'll run into the same origin policy error.
There is a way to make a request to that URL and get around the same origin policy. Put something like a PHP script on your own domain that makes a request to http://cabbagetexter.com/send.php and then call your own script from the javascript.
If your host supports PHP and cURL a script like this would do the job:
<?php
$url="http://cabbagetexter.com/send.php";
$post="";
if(strstr($url,"?")){
$split=explode("?",$url);
$url=$split[0];
$post=$split[1];
}
$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 0);
if($post!=""){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}else{
curl_setopt($ch, CURLOPT_POST, 0);
}
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch);
curl_close($ch);
print $result;
?>

Categories

Resources