I'm creating a form to send emails with the recaptcha. Everything was working perfectly, but I noticed that the recaptcha v3 only lasted 3 minutes and needed to reset. From there it started to give a "missing-input-response" error.
index.php
<script>
grecaptcha.ready(function() {
grecaptcha.execute('key', {action: 'homepage'}).then(function(token) {
document.getElementById('g-recaptcha-response').value=token;
});
});
</script>
<script>
var callback = function() {
grecaptcha.render('id-of-render-element', {
'sitekey': 'key',
'expired-callback': expCallback
});
};
var expCallback = function() {
alert("Your recatpcha has expired, please verify again ...");
setInterval(function(){ grecaptcha.reset(); }, 5 * 60 * 1000 );
};
</script>
<div id="id-of-render-element"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=callback&render=explicit" async defer></script>
class captcha
<?php
class Captcha{
public function getCaptcha($SecretKey){
$Resposta = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=key&response={$SecretKey}");
$Retorno = json_decode($Resposta);
return $Retorno;
}
public function returnCaptcha(){
echo "entrou calss_captcha";
$EnviaMail = False;
$ObjCaptcha = new Captcha();
$Retorno=$ObjCaptcha->getCaptcha($_POST['g-recaptcha-response']);
var_dump($Retorno);
if($Retorno->success == true && $Retorno->score > 0.5){
$EnviaMail = True;
}else{
$EnviaMail = False;
}
return $EnviaMail;
}
}
?>
As per the user comment working for Version 2. You need to specify additional parameters to the file_get_contents function call and If your site has SSL then setting the context options.
class Captcha{
public function getCaptcha($SecretKey){
if($SecretKey){
// Input data
$secret = 'SECRET_KEY';
$response = $SecretKey;
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$post_data = http_build_query(
array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteip
)
);
$options=array(
// If site has SSL then
'ssl'=>array(
// In my case its /etc/ssl/certs/cacert.pem
'cafile' => '/path/to/cacert.pem',
'verify_peer' => true,
'verify_peer_name' => true,
),
'http' =>array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create( $options );
$Resposta = file_get_contents( $url, false, $context );
$Retorno = json_decode($Resposta);
return $Retorno;
}
}
public function returnCaptcha(){
echo "entrou calss_captcha";
$EnviaMail = False;
$ObjCaptcha = new Captcha();
$Retorno=$ObjCaptcha->getCaptcha($_POST['g-recaptcha-response']);
var_dump($Retorno);
if($Retorno->success == true && $Retorno->score > 0.5){
$EnviaMail = True;
}else{
$EnviaMail = False;
}
return $EnviaMail;
}
}
Related
So basically I need to submit this quick-interest-slider form without page reload - https://loancalc.000webhostapp.com , this isn't my code, i'm not too experienced with wordpress or php.
After adding this $('.qis-form').on('submit'... code the slider continues to reload the page once i've clicked "apply now".
I don't know exactly what in the code I should be working with but i'm told the functions are...
qis-loop (validates and processes the form), qis_process_form also processes the form and sends email.
function qis_loop($atts) {
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
qis_process_form
function qis_process_form($values) {
global $post;
$content='';
$register = qis_get_stored_register($values['formname']);
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$qis_messages = get_option('qis_messages');
$application = qis_get_stored_application_messages();
if(!is_array($qis_messages)) $qis_messages = array();
$ip=$_SERVER['REMOTE_ADDR'];
$url = $_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
$page = get_the_title();
if (empty($page)) $page = 'Unknown Page';
$period = $values['loan-period'] == 1 ? $settings['singleperiodlabel'] : $settings['periodlabel'];
if (!$period) $period = $settings['period'];
$values['loan-amount'] = $settings['currency'].$values['loan-amount'];
$values['loan-period'] = $values['loan-period'].' '.$period;
$radio = explode(',',$register['radiolist']);
$values['yourradio'] = $radio[$values['radiooption']];
for ($i=1;$i<=3;$i++) {
if ($values['check'.$i]) $checks .= $register['check'.$i] . '<br>';
}
if ($checks) $values['yourchecks'] .= substr($checks, 0, -4);
$values['sentdate'] = date_i18n('d M Y');
$values['timestamp'] = time();
if ($register['storedata']) {
$newmessage = array();
$arr = array(
'reference',
'yourname',
'youremail',
'yourtelephone',
'yourmessage',
'yourchecks',
'yourradio',
'yourdropdown',
'yourconsent',
'loan-amount',
'loan-period',
'confirmation',
'formname',
'sentdate',
'timestamp'
);
foreach ($arr as $item) {
if ($values[$item] != $register[$item]) $newmessage[$item] = $values[$item];
}
$qis_messages[] = $newmessage;
update_option('qis_messages',$qis_messages);
}
if (!$auto['notification']) {
qis_send_notification ($values);
}
if (($auto['enable'] || $values['qis-copy']) && !$application['enable']) {
qis_send_confirmation ($auto,$values,$content,$register);
}
if ($register['qis_redirect_url']) {
$location = $register['qis_redirect_url'];
echo "<meta http-equiv='refresh' content='0;url=$location' />";
exit;
}}
The data is validated in qis_verify_application
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
If it passes validation the form is then processed in qis_process_application.
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
I have made an ajax call here
jQuery('.qis-form').on('submit', function(event){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else if (email == ""){
$("input#youremail").focus;
return false;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});
After hunting down your html, you will want to call it on the APPLY click NOT form submit.
jQuery(document).on('click','.toggle-qis a', function(event){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
return false;
});
I have this function where on onkeyup it verifies the mobile number whether it exists in the database already or not now the issue is even if the response is "true" it will always show as false
PHP
elseif ($action == 'check_mobile_phone')
{
$mobile = trim($_GET['mobile']);
$mobile = json_str_iconv($mobile);
if (mobile_register($mobile))
{
echo 'false';
}
else
{
echo 'true';
}
}
Ajax Call
function checkMobilePhone(mobile)
{
if (mobile == '')
{
error.find('#mobile_notice_text').html('Mobile number cant be empty.');
submit_disabled = true;
}
else if (!Utils.isMobile(mobile))
{
error.find('#mobile_notice_text').html('Please enter mobile number in local format.');
}
if( submit_disabled )
{
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
return false;
}
Ajax.call( 'user.php?act=check_mobile_phone', 'mobile=' + mobile, check_mobile_callback , 'GET', 'TEXT', true, true );
}
Response
function check_mobile_callback(result)
{
var logform = $('form[name="formUser"]');
var error = logform.find('#mobile_notice');
if ( result === "true" )
{
document.forms['formUser'].elements['Submit'].disabled = '';
}
else
{
error.find('#mobile_notice_text').html('Phone number already exists.');
document.forms['formUser'].elements['Submit'].disabled = 'disabled';
}
}
function mobile_register($mobile)
{
$res = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['db']->table('users') .
" WHERE mobile_phone = '$mobile'");
return $res;
}
We are creating a screening tool and this is the questions part. There is a progressbar under the question with the time but it only fills the bar or shows the progress when you reload the page.
This is the code
public function screening(Request $request){
$user_test = User_test::find(Session::get('user_test_id'));
$test = $user_test->test;
var_dump($user_test->questionsLeft());
$time = floor((strtotime(date('Y-m-d H:i:s')) - strtotime($user_test->started_at))/60);
if($test->time <= $time){
$user_test->unanswered = array_sum($user_test->questionsLeft());
$user_test->finished_at = date('Y-m-d H:i:s');
$user_test->score = $user_test->calculateScore();
$user_test->save();
return Redirect::route('user.dashboard')->with('error', ['test timed out']);
}
//Get user test object
$test = $user_test->test;
$current = $test->test_subcategories()->sum('amount') - array_sum($user_test->questionsLeft()) + 1;
//Get next question
if(Session::get('question_id') == null){
$question = $user_test->getNextQuestion();
Session::flash('question_id', $question->id);
} else if(!$user_test->answers()->where('question_id', Session::get('question_id'))->exists()){
$question = Question::find(Session::get('question_id'));
} else {
$question = $user_test->getNextQuestion();
Session::flash('question_id', $question->id);
}
// Calculate time
if($user_test->started_at == null){
return Redirect::route('user.dashboard');
} else {
$time = round((strtotime(date('Y-m-d H:i:s')) - strtotime($user_test->started_at))/60);
}
$lang = Sentinel::check()->text_lang_code;
return view('screening.test', array(
'test' => $test,
'question' => $question,
'lang' => $lang,
'time' => $time,
'current' => $current
));
}
This is the progressbar
<progress value="{{$time}}" max="{{$test->time}}"></progress>
Filling/updating progress bar is front-end job.
You need ajax request to calculate and then based on response update progress bar using jQuery.
something like
you are getting response from ajax
$.ajax({
url: "{your path}",
})
.done(function( data ) {
jQuery('progress').attr('value',time);
jQuery('progress').attr('max',test.time);
});
This is how we managed to get it right
$(document).ready(function(){
var progress = $('progress');
progress.val();
progress.prop('max');
progress.data('time', progress.val());
function countTimer() {
if(progress.data('time') < progress.prop('max') + 10){
progress.val(progress.val()+1);
progress.data('time', progress.data('time')+1);
} else {
location.reload();
console.log('timed out');
}
}
var setinterval = setInterval(countTimer, 6 * 1000);
});
I am doing an AJAX call from a function. Everything works fine until the AJAX call(I tried console.log before the AJAX call that was executed). It calls a controller's index function from there it returns the JSON object
in view:
$.ajax({
type: "POST",
url: "<?php echo $this->Html->url('/proposals');?>",
data: form,
dataType: "json",
success: function(data){
//alert(data.id+'--'+data.msg);
console.log("test");
if(data.msg == 'success'){
var valueRemaining= $('#RemainingFunding').val() ;
if (valueRemaining <= 0 ) {
alert ('No Funds Remaining');
return false;
}
var valueSubmitted = $('#subtotal'+state).text();
var valueSubmitted = parseInt(valueSubmitted);
if (valueSubmitted != null || valueSubmitted != '') {
//var substract = valueRemaining - valueSubmitted;
//$('#RemainingFunding').val(substract);
}
//console.log( 'value of subtotao f = ' + subflt );
$('#ProposalId').val(data.id); //ajx_submit
$('#sum').val(data.propsum);
$('#ajx_submit').val(parseInt(tot_ajxsub)+1);
$("input:radio[id=ProposalAnotherLocationY]").prop('checked', false);
$('#fld_subtotal').val('0');
pastSubtotals += flttot;
console.log("test");
tableState=0;
//console.log( 'value of pastSubtotal = ' + pastSubtotals);
//$('#RemainingFunding'). val(intamtval);
}else if(data.msg == 'error'){
alert('Proposal budget can not be blank!!');
return false;
}else {
alert('no match');
}
return false;
//$("#form")[0].reset();
//Unterminated String constant fixed
}
});
Controller:
if ($this - > request - > isAjax()) {
$Proposalsum = $this - > DftsProposalbudget - > find('all', array('fields' => array('SUM(DftsProposalbudget.cy1) as cy1', 'SUM(DftsProposalbudget.cy2) as cy2', 'SUM(DftsProposalbudget.cy3) as cy3 ', 'SUM(DftsProposalbudget.cy4) as cy4 ', 'SUM(DftsProposalbudget.cy5) as cy5', 'SUM(DftsProposalbudget.cy6) as cy6', 'SUM(DftsProposalbudget.cy7) as cy7', 'SUM(DftsProposalbudget.cy8) as cy8', 'SUM(DftsProposalbudget.cy9) as cy9', 'SUM(DftsProposalbudget.cy10) as cy10'), 'conditions' => array('DftsProposalbudget.proposal_id' => $LastID, 'DftsProposalbudget.user_id' => $UID), 'group' => 'DftsProposalbudget.proposal_id'));
$sum = 0;
echo '<pre>'.print_r($Proposalsum, true).
"</pre>";
if (!empty($Proposalsum)) {
foreach($Proposalsum[0][0] as $key => $value) {
//echo $sum += $value['0']['cy1'];
$sum += $value;
}
}
echo json_encode(array('msg' => 'success', 'id' => $LastID, 'propsum' => $sum));
exit(0); //json_encode('msg' => 'success', 'id' => '1');
In the network I get this message:
But it is not printing or working for anything that is in the block success.
I'm building a simple Wordpress "Course" website. Each user has to fully watch a video and when the video is complete it opens up the next one.
Currently, I have an update_user_meta tied to my video end() function but after I get that information into the database I'm unsure of how to pull it back out with get_user_meta to treat it almost like a user specific persistent session. Any thoughts from anyone? Or is my approach wrong?
This is what I have so far based off of this: https://patrickshampine.com/2014/updating-user-meta-admin-ajax-frontend/
html:
<dl class="accordion">
<dt><a class="checkbox" id="video-1" href="">Instructions</a></dt>
<dd class="video" id="dd-1">
<p id="video-message"></p>
<p id="wistia_id" class="wistia_embed" style="width:640px;height:360px;"></p>
</dd>
<div class="inactive" id="video-2fake"><a>History</a></div>
<dt><a id="video-2" class="hidden" href="">History</a></dt>
<dd class="video" id="dd-2">
<p id="video-message"></p>
<p id="wistia_id" class="wistia_embed" style="width:640px;height:360px;"></p>
</dd>
</dl>
In the theme functions.php:
add_action( 'wp_ajax_video_end', 'updateVideo' );
function video_scripts() {
$parameters = array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('video')
);
wp_enqueue_script('video-ajax', get_template_directory_uri().'/js/ajax.js', array('jquery'), null, true);
wp_localize_script('video-ajax', 'video', $parameters );
}
add_action('wp_enqueue_scripts', 'video_scripts');
function ajaxStatus($status, $message, $data = NULL) {
$response = array (
'status' => $status,
'message' => $message,
'data' => $data
);
$output = json_encode($response);
exit($output);
}
function updateVideo() {
if(empty($_POST) || !isset($_POST)) {
ajaxStatus('error', 'Nothing to update.');
} else {
$data = $_POST;
$dataString = $data['post'];
parse_str($dataString, $dataArray);
$nonce = $data['nonce'];
if(wp_verify_nonce($nonce, 'video') !== false) {
$user_ID = get_current_user_id();
$dataArray['watched'] = isset($dataArray['watched']) ? true : false;
if($user_ID != NULL) {
foreach($dataArray as $key=>$value) {
$status = update_user_meta($user_ID, $key, $value);
}
ajaxStatus('success', 'updated', $dataArray);
} else {
ajaxStatus('error', 'You are unauthorized to perform this action.', $dataArray);
}
} else {
ajaxStatus('error', 'Nonce check cannot fail.');
}
}
}
Then the javascript:
video1 = Wistia.embed("");
video2 = Wistia.embed("");
jQuery(document).ready(function($) {
var response;
var allPanels = $('.accordion > dd').hide();
$('.accordion > dt > a').click(function() {
allPanels.slideUp();
$(this).parent().next().slideDown();
if(this)
return false;
});
var watched = '<span>☑</span>',
visible1 = false,
visible2 = false,
$("#dd-1").show();
video1.bind("end", function () {
$( "#video-2").removeClass("hidden");
$( "#video-2fake").hide();
allPanels.slideUp();
$("#dd-2").slideDown();
if(!visible1) {
$( "#video-1" ).append( watched );
visible1 = true;
}
else {
if(visible1) {
$( "#video-1" ).remove( watched );
visible1 = false;
}
}
$.post( video.ajaxurl, {
action : 'video_end',
nonce : video.nonce,
post : $(this).serialize()
},
function(response) {
console.log(response);
responseSuccess(response);
});
return false;
function responseSuccess(data) {
response = JSON.parse(data);
if(response.status === 'success') {
$('#video-message').text(response.message);
} else {
$('#video-message').text(response.message);
}
}
});
video2.bind("end", function () {
$( "#video-3").removeClass("hidden");
$( "#video-3fake").hide();
allPanels.slideUp();
$("#dd-3").slideDown();
position = "2";
alert(position);
if(!visible2) {
$( "#video-2" ).append( watched );
visible2 = true;
}
else {
if(visible2) {
$( "#video-2" ).remove( watched );
visible2 = false;
}
}
$.post( video.ajaxurl, {
action : 'video_end',
nonce : video.nonce,
post : $(this).serialize()
},
function(response) {
console.log(response);
responseSuccess(response);
});
return false;
function responseSuccess(data) {
response = JSON.parse(data);
if(response.status === 'success') {
$('#video-message').text(response.message);
} else {
$('#video-message').text(response.message);
}
}
});
});