can't get json data with api - javascript

I am using below javascript and html to get the json data. But i can't make it work with this api.It just return blank result. I have checked the api link is working so i don't think is the server problem. Please help!
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="balance"></div>
javascript
$(function() {
$.ajax({
type: "GET",
url:"https://xmg.minerclaim.net/index.php?page=api&action=public",
dataType: "json",
success: function(data) {
console.log(typeof data); // -- Object
var json = data;
$('#balance').html(json.hashrate);
}
});
});
json data
{"pool_name":"minerclaim.net","hashrate":60185.64096,"workers":1056,"shares_this_round":168700,"last_block":1531882,"network_hashrate":61752985,"fee":1,"payout":"prop"}

As I mentioned above, you are getting bool(true) in your PHP output, because the usage of var_dump().
An example of a PHP file you could use:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://xmg.minerclaim.net/index.php?page=api&action=public");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 0);
$headers = array();
$headers[] = "Content-Type: application/json; charset=utf-8";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Some error:' . curl_error($ch);
die();
}
// You want your browser to think it's JSON, as we return as JSON
header("Content-Type: application/json; charset=utf-8");
echo($result);
curl_close($ch);
?>
You can copy + paste this into a new PHP file, point the $.ajax-url to that new file and see the magic happen. The example above works for me as I'm getting results back.
As for your javascript, you could also try to add contentType: "application/json", after `dataType: "json",", as this will make sure the content-type of the headers that are returned are set.

Related

Tableau Embed with jQuery and PHP passing parameters

I generally use Wordpress when building my internally facing dashboards with Tableau, but that will not work in this case so I am starting from scratch. I'm a novice with PHP and slightly above novice with jQuery, but I know my way around HTML. I need to pass an Okta javascript parameter into a Tableau embed. Below is my current code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var settings = {
url: "https://harmelin.okta.com/api/v1/users/me",
type: 'GET',
dataType: 'json',
contentType: 'application/json',
xhrFields: {
withCredentials: true
},
success: function (data) {
// alert(JSON.stringify(data));
},
error: function(err){
// alert(JSON.stringify(err));
}
}
jQuery.ajax(settings).done(function (success) {
console.log(success);
var raw = success.profile.login;
var email = raw.toLowerCase();
var $login = email.replace(/#[^#]+$/, '');
jQuery("#write-data").append($login);
});
</script>
</head>
<body>
<?php
// Tableau-provided functions for doing trusted authentication
require_once 'tableau_trusted.php';
?>
<div id="write-data"></div>
<?php
$user = 'jfedorowicz';
$server = 'dashboard1.harmelin.com';
$view = 'JoesPlayground/views/PTOStuff/Dashboard1?LCUsername=';
$theLogin = $login;
echo '<iframe src="';
echo get_trusted_url( $user,$server,$view$theLogin );
echo '" width="400" height="400"> </iframe>';
?>
</body>
Two problems:
1) What I am looking to do is pass $login (javascript variable) into $view. I 100% know that I did not do this right, but I cannot test because problem two.
2) I'm returning a 500 error: "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" which I assume is a Tableau error but I cannot figure it out.
Any ideas? Thanks.
To generate authorization token you can use given code.
This code is working fine with all version upto 2018.3
/* PHP code to generate auth token */
$url = $dashboardURL . '/trusted';
$fields_string = "trusted_site=&username=" . $username;
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$token = curl_exec($ch);
Now just pass this token with dashboard url in your view/html file.

Javascript setInterval method return always the same result from PHP method but I need changed data

So my problem is that I need to update some data from other site, and for calling that data I have php function where is the URL as parameter. ..So in JS I create a function that is in cycle with setInterval where I call that php function with URL parameter where are data stored, but it always return the same data..(data is actually playing track on stream, so data changed every +- 3 minutes) Data changes only on refresh page (f5) ..but I need update that data in background ..
this is the PHP function
function get_content($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
$data = str_replace(",,","},",$data);
$data = str_replace("}}]}}","}]}}",$data);
$data = str_replace("]}}","}]}}",$data);
$data = str_replace(",}}","}}}",$data);
$data = str_replace("}}]}}","}]}}",$data);
return $data;
In js I call in setInterval cycle only console.log to show result of php function..
console.log(<?php echo (get_content("http://server1.internetoveradio.sk:8809/status-json.xsl"));?>["icestats"]["source"])
Well, yeah. The PHP only gets called once in this case, the one time you echo out the contents of get_content();
If you want to get the content over and over again, use XmlHTTPRequest to call a PHP file which then returns the the result of get_content();
jQuery implements ajax ( XmlHTTPRequest ) to do exactly that.
jQuery.ajax({
url: "http://path.to/your_script.php",
method: "get",
complete: function( response ){
console.log(response);
}
});
edit:
Create a new .php file and paste this:
<?php
function get_content($URL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URL);
$data = curl_exec($ch);
curl_close($ch);
$data = str_replace(",,","},",$data);
$data = str_replace("}}]}}","}]}}",$data);
$data = str_replace("]}}","}]}}",$data);
$data = str_replace(",}}","}}}",$data);
$data = str_replace("}}]}}","}]}}",$data);
return $data;
}
echo get_content("http://server1.internetoveradio.sk:8809/status-json.xsl");
In your html, add this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery.ajax({
url: "http://path.to/your_script.php",
method: "get",
complete: function( response ){
console.log(response);
}
});
});
</script>
This is the most rudimentory version, but it should point you in the right direction hopefully.

Re-writing json api curl from javascript to php

Hello great stackoverflow, am trying to re-write the api below from javascript to php in other to be able to make json curl but displays error below
Warning: curl_setopt() expects exactly 3 parameters, 4 given in C:\xampp\htdocs\firstcare\curl.php on line 15
js curl
curl -X POST
"http://my_api.com/accesstoken?grant_type=client_credentials"
-H "Content-Type: application/x-www-form-urlencoded"
-d 'client_id=$myClient_id'
-d 'client_secret=$myClient_secret
php curl conversion
<?php
// 0 means unlimited timeout
ini_set('max_execution_time', 0);
$data = array(
'Content-Type' => 'application/x-www-form-urlencoded',
'client_id' => 'myclient_id',
'client_secret' => 'myclient_secret'
);
$url='http://my_api.com/accesstoken?grant_type=client_credentials';
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url,$data);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
echo '<pre>' . print_r($json, true) . '</pre>';
?>
Thanks
Error was thrown because curl_setopt requires 3 parameters - you've passed 4 here:
curl_setopt($ch, CURLOPT_URL,$url,$data);
May I suggeest guzzlehttp, wrapper for curll...also u seem to be passing headers in $data as the forth paramenter remove $data. If u want to sent cllient id as GET append the $url with http_build_query()
Try these codes
<?php
// 0 means unlimited timeout
ini_set('max_execution_time', 0);
$postdata = array(
'client_id' => 'myclient_id',
'client_secret' => 'myclient_secret'
);
$header = array(
'Content-Type' => 'application/x-www-form-urlencoded',
);
$url='http://my_api.com/accesstoken?grant_type=client_credentials';
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, true); //if you want headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result=curl_exec($ch);
curl_close($ch);
$json = json_decode($result, true);
echo '<pre>' . print_r($json, true) . '</pre>';
?>

How do I pass a PHP array to a JavaScript variable?

I have the following JavaScript that sends parameters to a PHP file:
function getOutput()
{
$.ajax({
url:'myPHPFile.php',
data:{APIKey:$APIKey,Password:$APIPass,Alias:$Alias,DataCenter:$DataCenter},
type:'POST',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function ()
{
$('#output').html('Bummer: there was an error!');
}
});
return response.responseText;
}`
Which changes the following HTML to the output of the PHP file:
test
Here is the PHP
<?php
// echo nl2br("\nIntializing api.php \n");
// DATA SECTION
$APIKey = $_POST["APIKey"];
$APIPass = $_POST["Password"];
$AccountAlias = $_POST["Alias"];
$dataCenter = $_POST["DataCenter"];
$data = array(
"APIKey" => $APIKey,
"Password" => $APIPass,
);
$url_send = 'https://api.ctl.io/REST/Auth/Logon/';
$json_data = json_encode($data);
function sendPostData($url, $post, $cook = null){
// echo "Beginning sendPostData($url, $post, $cook)";
$ch = curl_init($url);
$headers= array('Accept: application/json','Content-Type: application/json');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if (!empty($cook))
{
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json','Cookie:'.$cook));
}
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
};
$myresult = sendPostData($url_send, $json_data);
// print_r ($myresult);
$decodedresult = json_decode($myresult);
// print_r ($decodedresult);
'/reply-(.*?)-private/';
preg_match_all('/Tier3(.*?)path=/', $myresult, $matches);
$cookies = array();
foreach($matches[0] as $item)
{
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
$prefix = 'Tier3.API.Cookie=';
$cookie = implode(" ",$matches[0]);
// Call the customer server list
$data = array(
'AccountAlias' => $AccountAlias,
'Location' => $dataCenter
);
$data_url = 'https://api.ctl.io/REST/Server/GetAllServersForAccountHierarchy/';
$data_string = json_encode($data);
$dataResult = sendPostData($data_url,$data_string, $cookie);
print_r($dataResult);
return $dataResult;
`
How can I get the $dataResult PHP array into a javascript variable so I can parse it? It is a big JSON response from an API.
Thanks.
Ajax calls are (normally) asynchronous, this means that the return response.responseText; will be executed immediately and should even raise an error related to response being undefined.
You'll have the response in the complete event of the ajax call and is inside there where you should go on with the execution of the script. jQuery will parse the JSON automatically and response will be the resulting object.
At the other side, the PHP script should just print the result of json_encode() and nothing else in order for the response to be valid JSON.

Jquery/AJAX&PHP Domain checker

I'm trying to build a domain availability checker.
My PHP code is the following:
<?php
$domain = $_GET["domname"];
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data('http://freedomainapi.com/?key=XXXXXXX&domain=' . $domain);
echo $returned_content;
?>
When called as such: /domchek.php?domname=google.com
The JSON output is:
{"status":"success","domain":"google.com","available":true}
The JQuery im using to call the script is as follows:
$.get("domchek.php?domname=google.com", {data: "available"}, function(json) {
$("html").html(json);
});
I just want to return the availability not the entire JSON output. I have tried json.availability and a number of other things but can't figure it out. Also if there is a better method for this than .get() please suggest it.
UPDATE:
$.getJSON("domchek.php?domname=google.com", function(json) {
$("html").html(json.status);
});
The above works as does returning json.domain but trying to return json.available - which I require returns nothing..
Change this line:
$("html").html(json);
to:
$("html").html(json.status);
UPDATE: to force the GET request data type to JSON, change to:
$.get("domchek.php?domname=google.com", {data: "available"}, function(json) {
$("html").html(json);
}, 'json');

Categories