Jquery/AJAX&PHP Domain checker - javascript

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');

Related

How to use d3.js chart with data from coingeckoapi (json)

I'd like to create a chart with d3.js. Could someone tell me how to work with the jsondata[timestamp,price]. I get the data from coingeckoAPI and it looks like that:
{"prices":[[1649667011317,38721.07051511258],[1649667168163,38726.36780848938],[1649667622285,38750.30201896313],[1649667926510,38715.36968177588],[1649668246571,38705.597785934006],[1649668432287,38690.34512542588],[1649668897715,38620.57305041674],[1649669050953,38613.10740572825],[1649669284813,38568.32503183882],[1649669697192,38518.76279413846],[1649669982557,38491.21941297744],[1649670258121,38460.7219359208],[1649670606639,38417.38270710583],[1649670978757,38349.85248699985],[1649671244134,38336.437837571124],
thats my Php Code:
function history($url) {
$ch= curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$resp = curl_exec($ch);
if ($e= curl_error($ch)) {
echo $e;
}
else {
return $resp;
}
curl_close($ch);
}
and HTML:
<?php echo history("https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=eur&days=1");
?>
Please change HTML line to below
var data = <?php echo history("https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=eur&days=1");?>;
You may use JSON.parse if it gives any parsing error in javascript code.
var data = JSON.parse(<?php echo history("https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=eur&days=1");?>);
You read below link https://www.geeksforgeeks.org/how-to-pass-variables-and-data-from-php-to-javascript/

can't get json data with api

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.

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.

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.

Replace whateverorigin.org call with local proxy in php

I'm currently using whateverorigin.org in some javascript to retrieve a URL as a JSON object because a 3rd party site hasn't made one of their functions available via their JSON API.
I'd like to remove this dependancy from my website as whateverorigin.org breaks the HTTPS/SSL browser checks for secure content because it's a clear http call.
Has anyone done this? I haven't found an example of it anywhere.
Thanks in advance for a response!
Ok, so since I first typed up this question, I've now already found some examples and cobbled together a working proxy function in php... Feel free to use it for your own purposes!
<?php
// Sourced from: http://stackoverflow.com/questions/2511410/curl-follow-location-error
function curl_exec_follow(/*resource*/ &$ch, /*int*/ $redirects = 20, /*bool*/ $curlopt_header = false) {
if ((!ini_get('open_basedir') && !ini_get('safe_mode')) || $redirects < 1) {
curl_setopt($ch, CURLOPT_HEADER, $curlopt_header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirects > 0);
curl_setopt($ch, CURLOPT_MAXREDIRS, $redirects);
return curl_exec($ch);
} else {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
do {
$data = curl_exec($ch);
if (curl_errno($ch))
break;
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code != 301 && $code != 302)
break;
$header_start = strpos($data, "\r\n")+2;
$headers = substr($data, $header_start, strpos($data,"\r\n\r\n", $header_start)+2-$header_start);
if (!preg_match("!\r\n(?:Location|URI): *(.*?) *\r\n!",$headers, $matches))
break;
curl_setopt($ch, CURLOPT_URL, $matches[1]);
} while (--$redirects);
if (!$redirects)
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
if (!$curlopt_header)
$data = substr($data, strpos($data, "\r\n\r\n")+4);
return $data;
}
}
header('Content-Type: application/json');
$retrieveurl = curl_init(urldecode($_GET['url']));
$callbackname = $_GET['callback'];
$htmldata = curl_exec_follow($retrieveurl);
if (curl_error($retrieveurl))
die(curl_error($retrieveurl));
$status = curl_getinfo($retrieveurl, CURLINFO_HTTP_CODE);
curl_close($retrieveurl);
$data = array('contents' => $htmldata, 'status' => $status);
$jsonresult = json_encode($data);
echo $callbackname . '(' . $jsonresult . ')';
?>
Hope this helps someone!

Categories