I am using google currency converter.All is doing fine but on page refresh I can't get the input value set to its original value.Below is my code.
<script src = "js/CurrencyConverter.js" type="text/javascript"></script>
<select id="FromCurrency" class="CurrencyDropDown"></select>
<input type = "text" id = "UnitPrice" value="enter amount"/>
</br>
<select id="ToCurrency" class = "CurrencyDropDown"></select>
<input type = "text" id = "destinationPrice" value="result"/>
<script>
$(document).ready(function(){
$('select#ToCurrency').change(function(){
convertcurrency();
})
});
function convertcurrency(){
var url = $('input[type=hidden]').val();
var priceunit = $('input#UnitPrice').val();// alert(priceunit);
var fromcurrencycode = $('select#FromCurrency').val(); //alert(fromcurrencycode);
var tocurrencycode = $('select#ToCurrency').val();// alert(tocurrencycode);
ConvertCurrency(url, priceunit,fromcurrencycode,tocurrencycode);
}
function ConvertCurrency(Url , PriceUnit,fromCurrencyCode,toCurrencyCode){
$.ajax({
url: '<?php echo site_url('curchange')?>',
type : 'POST',
dataType: "html",
data : {unitprice : PriceUnit, fromcode : fromCurrencyCode, tocode : toCurrencyCode},
success: function (data) {
if(data != '')
$('input#destinationPrice').val(data);
else
alert('Cannot convert');
},
error : function(){
alert('Error in Loading Data');
}
});
return false;
}
</script>
in CurrencyConverter.js I have list of countries which on window load is loaded to dropdown.
curchange.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Curchange extends CI_Controller{
function __construct() {
parent::__construct();
}
function index(){
$unit = $this->input->post('unitprice');
$from = $this->input->post('fromcode');
$to = $this->input->post('tocode');
$url = 'http://www.google.com/ig/calculator?hl=en&q='.$unit.$from.'=?'.$to;
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('"', $rawdata);
$error = explode(' ', $data[5]);
if(empty($error[0])){
$data = explode(' ', $data[3]);
$var = round($data[0], 3);
}else{
$var = '';
}
echo $var;
}
}
?>
The code is working fine.Currency is being converted but when I change the currency and then refresh the page instead of showing input value as 'enter amount' and 'result' the input html tag is showing the initial values.Why?
any help/suggestions are welcome.
Write two statements after $(document).ready(function(){
like:
$(document).ready(function(){
$("#UnitPrice").val("enter amount");
$("#destinationPrice").val("result");
});
It will set default value on page refresh
Related
I have the code from below, once the form is sended I want to check in it if the user passed the recaptcha test. How do i do it? Searched many things and i can't find a way that works for me ..
<html>
<head>
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var onloadCallback = function() {
grecaptcha.render('example3', {
'sitekey' : '6LdlRIgaAAAAAJXOu3EsuGVnKVjmSaWfSbuwSHLI',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// here I want to verify if the use user passed the recaptcha
{
some code
}
}
?>
<form method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
You should lookup the Server side validation docs for reCAPTCHA:
https://developers.google.com/recaptcha/docs/verify
You have to send an API request via PHP CURL, as stated in the docs:
URL: https://www.google.com/recaptcha/api/siteverify METHOD: POST
So something like this:
function validate_captcha($secret, $response, $remoteip) {
$captcha_url = "https://www.google.com/recaptcha/api/siteverify";
$captcha_url .= "?secret=".$secret;
$captcha_url .= "&response=".$response;
$captcha_url .= "&remoteip=".$remoteip;
$ch = curl_init($captcha_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$response=json_decode($data,true);
if ($response["success"]) {
return true;
}
else {
return false;
}
}
And you call the function like this:
$captcha_is_ok = validate_captcha(
"......mySecret.....",
$_POST['g-recaptcha-response'],
$_SERVER['REMOTE_ADDR']);
if ($captcha_is_ok) {
... do something cool ...
} else {
... don't do something cool ...
}
I am trying to figure out how to send back a value to the Ajax popup box. Currently, the value that gets returned is just the JSON that comes back from the API call. I would much rather use jsondecode to pull out a specific value and have that return, or... lets not even get that complex. I just want to set a variable equal to some message such as "API GET complete" and return that to the Ajax box. This will also help with troubleshooting so I can return a variable to see if things are working. As I said, currently the Ajax popup just displays the JSON that comes back from the API call. This is my first time working with both Ajax and curl_setopt so if you can please make recommendations with examples, that would be fantastic! Thank you!
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'auto.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
alert(response);
});
});
});
</script>
</head>
<body>
<input type="submit" class="button" name="test" value="Test" />
</body>
</html>
auto.php
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'Test':
Test();
break;
case 'to_the_n':
to_the_n();
break;
}
}
function Test() {
$ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
$result = curl_exec($ch);
$message = "Yay it worked" //Send this message back to Ajax popup, not the API reply
exit;
}
?>
* UPDATE *
* UPDATE *
You can just echo the value from php and it will be alerted in the Ajax success function.
echo 'Yay it worked!! ';
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'Test':
if(Test() == true) {
echo('yay it worked!! ');
exit;
}
break;
case 'to_the_n':
to_the_n();
break;
}
}
function Test() {
$ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
$result = curl_exec($ch);
return true;
}
?>
Recently tasked to monitor external webpage response/loading time via CACTI. I found some PHP scripts that were working (pageload-agent.php and class.pageload.php) using cURL. All was working fine until they requested it to be transferred from LINUX to Windows 2012R2 server. I'm having a very hard time modifying the scripts to work for windows. Already installed PHP and cURL and both working as tested. Here are the scripts taken from askaboutphp.
class.pageload.php
<?php
class PageLoad {
var $siteURL = "";
var $pageInfo = "";
/*
* sets the URLs to check for loadtime into an array $siteURLs
*/
function setURL($url) {
if (!empty($url)) {
$this->siteURL = $url;
return true;
}
return false;
}
/*
* extract the header information of the url
*/
function doPageLoad() {
$u = $this->siteURL;
if(function_exists('curl_init') && !empty($u)) {
$ch = curl_init($u);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, false);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
$pageBody = curl_exec($ch);
$this->pageInfo = curl_getinfo($ch);
curl_close ($ch);
return true;
}
return false;
}
/*
* compile the page load statistics only
*/
function getPageLoadStats() {
$info = $this->pageInfo;
//stats from info
$s['dest_url'] = $info['url'];
$s['content_type'] = $info['content_type'];
$s['http_code'] = $info['http_code'];
$s['total_time'] = $info['total_time'];
$s['size_download'] = $info['size_download'];
$s['speed_download'] = $info['speed_download'];
$s['redirect_count'] = $info['redirect_count'];
$s['namelookup_time'] = $info['namelookup_time'];
$s['connect_time'] = $info['connect_time'];
$s['pretransfer_time'] = $info['pretransfer_time'];
$s['starttransfer_time'] = $info['starttransfer_time'];
return $s;
}
}
?>
pageload-agent.php
#! /usr/bin/php -q
<?php
//include the class
include_once 'class.pageload.php';
// read in an argument - must make sure there's an argument to use
if ($argc==2) {
//read in the arg.
$url_argv = $argv[1];
if (!eregi('^http://', $url_argv)) {
$url_argv = "http://$url_argv";
}
// check that the arg is not empty
if ($url_argv!="") {
//initiate the results array
$results = array();
//initiate the class
$lt = new PageLoad();
//set the page to check the loadtime
$lt->setURL($url_argv);
//load the page
if ($lt->doPageLoad()) {
//load the page stats into the results array
$results = $lt->getPageLoadStats();
} else {
//do nothing
print "";
}
//print out the results
if (is_array($results)) {
//expecting only one record as we only passed in 1 page.
$output = $results;
print "dns:".$output['namelookup_time'];
print " con:".$output['connect_time'];
print " pre:".$output['pretransfer_time'];
print " str:".$output['starttransfer_time'];
print " ttl:".$output['total_time'];
print " sze:".$output['size_download'];
print " spd:".$output['speed_download'];
} else {
//do nothing
print "";
}
}
} else {
//do nothing
print "";
}
?>
Thank you. any type of assistance is greatly appreciated.
Following this post How to get a user's Instagram feed , i use it to display the last image
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/123456789/media/recent/?access_token=123456789.123asdsd.asdadasdas23423423&count=1");
$result = json_decode($result);
foreach ($result->data as $post) {
if(empty($post->caption->text)) {
// Do Nothing
}
else {
// Display img
}
}
How can be loaded asynchronous? Sometimes is takes even 2-3s to load and delays the entire page to be displayed. Tks for you time and help!
EDIT
tks to #steve, i solved it by query instagram api once per hour and save the response to instagram.json
get-social-media.php
function get_instagram($user_id=instagram_user_id,$count=1){
$instaurl = `https://api.instagram.com/v1/users/`.$user_id.`/media/recent/?access_token=instagram_access_token&count=`.$count;
$instacache = `instagram.json`;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL,$instaurl);
$instadata=curl_exec($ch);
curl_close($ch);
if(file_exists($instacache) && filemtime($instacache) > time() - 60*30){
//echo "ok instagram";
} else {
$jsonInstaData = json_decode($instadata,true);
file_put_contents($instacache,json_encode($jsonInstaData));
}
}
echo get_instagram();
and that ajax for frontend social-media-block.phtml (magento & bootstrap)
jQuery(document).ready(function($) {
$("#instagram-img").html("");
$.ajax({
type: "GET",
async: true,
contentType: "application/json; charset=utf-8",
url:"resources/socialmedia-cache/instagram.json",
dataType: "json",
cache: true,
beforeSend: function () {
$("#loading").show();
},
success: function (data) {
console.log(data);
$("#loading").hide();
if (data == "") {
$("#InstaContainer").hide();
} else {
$("#InstaContainer").show();
for (var i = 0; i < data["data"].length; i++) {
var dataForJson = JSON.stringify(data.data[i]);
var date = new Date(parseInt(data.data[i].caption.created_time) * 1000);
$("#instagram-img").append("<a target=`_blank` href=`" + data.data[i].link + "` title=`" + data.data[i].caption.text + "`><img src=`" + data.data[i].images.low_resolution.url + "` class=`img-responsive socialmedia-img`></img></a>");
$("#instagram-img").append("<p align=`left`><script>" + "jQuery(document).ready(function() { jQuery(`a.timeago`).timeago();});" + "</" + "script><a class=`timeago` style=`color:#484848;` title=`" +(date.getMonth()+1)+"/"+date.getDate()+"/"+date.getFullYear()+", "+date.getHours()+":"+date.getMinutes()+ "`>" +(date.getMonth()+1)+"/"+date.getDate()+"/"+date.getFullYear()+", "+date.getHours()+":"+date.getMinutes()+ "</a></p>");
}
}
}
});
});
this also works for facebook
for pinterest, i use http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1&q=https://www.pinterest.com/MyPinterest/feed.rss , a quick solution to convert the rss to json. since i need images larger than 236px, next parsed is 736px. also, the img src needs to be extracted from content
var string = data.responseData.feed.entries[i].content;
var filtered = string.replace('/236x/', '/736x/');
var source = filtered.match(/src\s*=\s*"(.+?)"/);
probably not the best code, but at least is a working solution.
Thanks guys and gals got it working
//create a function
function get_stock_data($symbol){
//set up the url to be called
$revenue_url = "http://finance.yahoo.com/q/is?s=".$symbol;
//curl call:
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $revenue_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// grab URL and pass it to the browser
$result = curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
//finish by returning the result
return $result;
}
//REQUEST WILL BE POPULATED IF EITHER GET OR POST IS SET!
$data = null; // this will hold our data, declared here for accessibility
if(isset($_REQUEST['symbol']) && $_REQUEST['symbol'] != ''){
//call our get_data function
$data = get_stock_data($_REQUEST['symbol']);
}
// data returned from our get_stock_data() call.
$ppe = $data['ppe'];
$revenue = $data['revenue'];
$income = $data['income'];
$market_cap = $data['market_cap'];
$depreciation = $data['depreciation'];
$rate_of_return = $data['rate_of_return'];
$rate_of_return_w_ppe = $data['rate_of_return_w_ppe'];
$debt = $data['debt'];
}
Add following code in your update button(page) script at last
<script type="text/javascript">
var php_var = "<?php echo $symbol; ?>";
locationInfo="stock_next.php?symbol="+php_var;
setTimeout(function(){
location =locationInfo
},2000)
</script>
Your page will be automatically updated after some seconds