Uncaught ReferenceError: $result is not defined - javascript

The below script means for cross domain and pull out the JSON result for the select menu. Currently the CURL able to echo out the $result but unable to display in the select menu with console log error: Uncaught ReferenceError: the $result is not defined. I need help on diagnosing this matter.
<?php
$data_string = json_encode($data, JSON_UNESCAPED_SLASHES);
$ch = curl_init('https://xxxxxxx.com');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)
));
$result = curl_exec($ch);
echo ($result);
?>
<script>
let dropdown = $('#title-dropdown');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choose Title</option>');
dropdown.prop('selectedIndex', 0);
const url = $result;
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.description).text(entry.display_name));
})
});
</script>

You aren't outputting the PHP $result variable to the Javascript, you're telling javascript to look for a variable that doesn't exist. Try
const url = '<?php echo $result ?>';
it's been a while since I've done any PHP but that should at least put you on the right track if it isn't 100% correct.

Change this
const url = $result;
$.getJSON(url, function (data) {
$.each(data, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.description).text(entry.display_name));
})
});
to this:
const json = $.parseJSON('<?php echo $result; ?>');
var result = json.result;
for (var i = 0; i < result.length; i++) {
for (var key in result[i]) {
console.log('KEY: ' + key + 'VALUE: ' + result[i][key]);
}
}

Related

How to call a JavaScript function from PHP if click and curl?

I have a little project in which I try to fetch data from a domain and put this information in input fields.
The Curl function is good and working. However, the jQuery script if not working or filling the input fields. If I use $url = "http://domain..."; , all is working on page load but if I use an input field with a button and post form, the fields are empty. The curl is working and gives the full page back.
How I can load the script with the same button but after load the curl script?
Button:
<form action="" method="POST">
<label for="name">URLinput</label>
<input type="url" id="inf_endpoint" name="inf_endpoint" value="" />
<button type="submit" name="mytest">Test This</button>
</form>
What I have tried:
<?php
if(isset($_POST['mytest'])){
$url=$_POST['inf_endpoint'];
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL, html_entity_decode($url));
$data = curl_exec($ch);
if($result === false){
echo 'Curl error: ' . curl_error($ch);
}else{
echo 'All is good';
?>
<script>
jQuery.ajax({
url: '<?php echo site_url('admin/matches/manage'); ?>',
type: 'GET',
success: function(res) {
var data = jQuery.parseHTML(res);
jQuery(data).find('div.right').each(function(){
$('#date').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.team a:first').each(function(){
$('#team1').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.team a:nth-child(2)').each(function(){
$('#team2').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.match_head .left a:first').each(function(){
$('#league').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.score').each(function(){
$('#result').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.team_logo a:first').each(function(){
$('#logo1').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.oppo2 a:first').each(function(){
$('#logo2').val(jQuery(this).html());
});
}
});
</script>
<?php
}
curl_close($ch);
echo $data;
}
?>
But this is working on Page load. But not with a if statement with click
$url="https://thedomain";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL, html_entity_decode($url));
$data = curl_exec($ch);
if($result === false){
echo 'Curl error: ' . curl_error($ch);
}else{
echo 'All is good';
}
curl_close($ch);
echo $data;
and
jQuery.ajax({
url: '<?php echo site_url('admin/matches/manage'); ?>',
type: 'GET',
success: function(res) {
var data = jQuery.parseHTML(res);
jQuery(data).find('div.right').each(function(){
$('#date').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.team a:first').each(function(){
$('#team1').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.team a:nth-child(2)').each(function(){
$('#team2').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.match_head .left a:first').each(function(){
$('#league').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.score').each(function(){
$('#result').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.team_logo a:first').each(function(){
$('#logo1').val(jQuery(this).html());
});
var data = jQuery.parseHTML(res);
jQuery(data).find('div.oppo2 a:first').each(function(){
$('#logo2').val(jQuery(this).html());
});
}
});
Without click function > The Page is loading and fill the fields.
cURL is a security risk even when your dealing with your servers but let me try to point out some items. Someone can get between you and your curl, magic can happen.
Your first line I don't think it's doing the proper check
<?php
if(isset($_POST['mytest'])){
change to
<?php
if(isset($_POST['Submit'])){
or even better to
if($_SERVER['REQUEST_METHOD']=='POST'){
Secondly, I can't see where $result is being set, change the following
if($result === false){
to
if(empty($data)){
I hope that solves missing points

How to reset Google reCaptcha?

Here is my PHP Code:
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => '',
'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);
}
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
die('MF005');
} else {
if ($mail->send()) {
$send_arEmail = $autoresponder->Send();
}}
and here is my JavaScript code:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmit(token) {
document.getElementById("i-recaptcha").submit();
}
</script>
This is my captcha:
<div class="g-recaptcha" data-sitekey="" ></div>
and this is button submit:
<button class="button rounded" type="submit" data-callback="onSubmit">Send</button>
This is also my form id:
<form id="i-recaptcha">
This above function is working, but after submit form, still captcha is checked, I want to reset it to unchecked once user click on submit button.
You can use it like this. It's based on version.
Version 3
grecaptcha.ready(function() {
grecaptcha.execute('SITE_KEY', {action: 'homepage'}).then(function(token){
$('#token').val(token);
});
});
Version 2
grecaptcha.reset();
Version 1
Recaptcha.reload();

Steam loading inventory trying until its loaded

Here is the code i wrote so far:
<?php
do {
//If this isn't the first time in the loop, pause for a second to prevent spamming their servers
if(isset($statusCode)){
sleep(1);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://steamcommunity.com/profiles/76561198258195397/inventory/json/730/2");
//The curl request should return the body of the text
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Apparently the URL provided initially returns with a 3XX response, this option follows the redirection.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$steamData = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//Repeat this command until we get a successful request
//Note that this is slightly naive - Any 2XX should be deemed successful.
} while ($statusCode !== 200);
//$steamData = file_get_contents("http://steamcommunity.com/profiles/76561198258195397/inventory/json/730/2");
$data = json_decode($steamData, true);
$items = $data['rgDescriptions'];
foreach($items as $key => $item){
$market_hash_name = $item["market_hash_name"];
$market_hash_name = htmlentities($market_hash_name, ENT_QUOTES, 'UTF-8');
$sql = "SELECT price FROM itemprice WHERE market_hash_name='".$market_hash_name."'";
$result = $conn->query($sql);
$itemprice = "-";
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
if($row['price']>0.02){
$itemprice = $row['price'];
$itemprice = floatval($itemprice);
$itemprice = $itemprice*1.05;
$itemprice = round($itemprice, 3);
}else{
$itemprice = 0;
}
}
}
echo '<div class="items"><center><img src="http://steamcommunity-a.akamaihd.net/economy/image/' . $item["icon_url"] . '" height="192" width="256"></center><div><center><h5 style="color:#'.$item["name_color"].'">'.$item["market_name"].' - <strong><b><a style="color:green">$'.$itemprice.'</a></b></strong></h5></center></div></div>';
}
?>
So sometimes its just loading and after around 20sec it stops the chrome giving me an error like i dont have internet connection, and i cant open any page on the site for 1min.But after that everything is okay...Does anybody know another alternative to get the inv?
here is a ss of the output on the site: https://gyazo.com/80e9d1cf3e6dd0ae151a9f85cc1e0cf9

javascript mandatory data error in screenleap api

i have a json encoded data in a variable named $json, it looks like-
string(1243) "{"screenShareCode":"882919360",
"appletHtml":"",
"presenterParams":"aUsEN5gjxX/3NMrlIEGpk0=",
"viewerUrl":"http://api.screenleap.com/v2/viewer/882919360?accountid=mynet",
"origin":"API"}"
}
i need to pass this json data into javascript function, please see below
script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js">/script>
script type="text/javascript">
window.onload = function() {
var screenShareData = '?php echo $json;?>';
screenleap.startSharing('DEFAULT', screenShareData);
};
/script>
when i am trying to run this code it is giving me an error saying "missing mandatory screen share data".
How to solve this error?
i am following "https://www.screenleap.com/api/presenter"
It looks like $json is a string, you need to pass in a json object. Try the following:
window.onload = function() {
var screenShareData = '?php echo $json;?>';
screenleap.startSharing('DEFAULT', JSON.parse(screenShareData));
};
This is how you implement it based on the documentation
https://www.screenleap.com/api/presenter
<?php
// Config
$authtoken = '';
$accountid = '';
// 1. Make CURL Request
$url = 'https://api.screenleap.com/v2/screen-shares';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('authtoken:<authtoken>'));
curl_setopt($ch, CURLOPT_POSTFIELDS, 'accountid=<accountid>');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$json = json_decode($data, true);
?>
<!-- 2. Launch the Presenter App -->
<script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js"></script>
<script type="text/javascript">
window.onload = function() {
screenleap.startSharing('DEFAULT', JSON.parse('<?php echo $json; ?>'));
};
</script>
If this doesn't work, you got to report it to screenleap.
You should only need to actually parse the JSON if you want to access the values. Otherwise, just pass the response data right into the startSharing function, like this:
<?php
$url = 'https://api.screenleap.com/v2/screen-shares';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('authtoken:<your authtoken>'));
curl_setopt($ch, CURLOPT_POSTFIELDS, 'accountid=<your accountid>');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);
curl_close($ch);
$json = json_decode($data, true);
?>
<script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js"></script>
<script type="text/javascript">
window.onload = function() {
screenleap.startSharing('DEFAULT', <?php echo $data; ?>);
};
</script>
If you just insert your own accountid and authtoken (without leading spaces), that should work for you.

How to display instagram API response in javascript alert?

I am trying to send a delete request to instagram api using ajax but my current javascript code display the response in alert box as:
<pre></pre><pre></pre>
so i cant find the problem why delete request is not successful! if i call the same php script(doit.php) from the browser and pass it media id then the delete will be successful!
could any one tell me what is wrong with my current delete ajax request that fails to make delete request to instagram api?
Instagram API Docs for Deleting Like
sample api response:
{
"meta": {
"code": 200
},
"data": null
}
javascript:
<script>
function deleteLike(a,b)
{
alert("MediaID:"+a+"\nId:"+b);
var url = "./doit.php";
$.post(url, {
"method": "post",
//"method": "delete",
"MediaID": a,
}, function(data)
{
var ajaxResponse = data;
alert("Response:"+ajaxResponse);
if (data.meta.code == 200) {
alert("sucessDelete");
}
})
}
</script>
PHP CODE:
$MediaIDvar= $_POST["MediaID"];
//$MediaIDvar= $_GET["MediaID"];
$url2 = "https://api.instagram.com/v1/media/".$MediaIDvar."/likes?xxxxx";
$api_response2 = get_data2(''.$url2);
$record2 = json_decode($api_response2); // JSON decode
echo '<pre>' . print_r($api_response2, true) . '</pre>';
echo '<pre>' . print_r($record2, true) . '</pre>';
// to see what is in the $api_response and $record object
/* gets the data from a URL */
function get_data2($url2) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$MediaIDvar= $_POST["MediaID"];
$MediaIDvar= $_GET["MediaID"]; // => this will overwrite the previous $MediaIDvar
it will work if you call the php script with a GET variable, not through ajax using POST ;-)

Categories

Resources