CAPTCHA invalid-input-response - javascript

I'm trying to create a CAPTHCA for my forms on a website, but it always gives back "invalid-input-response".
I have the following front code for my form with captcha:
<script src="https://www.google.com/recaptcha/enterprise.js" async defer></script>
<script>
var onloadCallback = function() {
grecaptcha.enterprise.render('html_element', {
'sitekey' : '<?php echo G_RECAPTCHA_SITE_KEY?>',
'callback' : function(response) {
if(response){
// success
}
},
'theme' : 'dark'
});
};
</script>
<form>
...
<div id="html_element"></div>
</form>
<script src="https://www.google.com/recaptcha/enterprise.js?onload=onloadCallback&render=explicit" async defer></script>
End the backend side:
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
// error
return false;
}
$secretKey = G_RECAPTCHA_SECRET_KEY;
// post request to server
$url = 'https://www.google.com/recaptcha/api/siteverify'
. '?secret=' . urlencode($secretKey)
. '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response,true);
// should return JSON with success as true
if(!$responseKeys["success"]) {
var_dump($responseKeys);
}
and the output is:
array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "invalid-input-response" } }
G_RECAPTCHA_SITE_KEY and G_RECAPTCHA_SECRET_KEY are defined correctly, i checked them several times.
Do you have any suggestions? Is there something wrong with the code, or is it maybe something wrong with how i set up my reCAPTCHA Enterprise account?
Thanks in advance!

Related

Wordpress how to use Ajax to show new data returned from successful insert_post()?

After a successful Ajax insert of an entry, I would like to see what the ID and url of that same entry is and display it in a modal window without refreshing the page
Any way to get this data from success: function (response) {}? This is the code I have to make a new entry with ajax which works perfect:
<script>
$("#enquiry_email_form").on("submit", function (event) {
event.preventDefault();
var form= $(this);
var ajaxurl = form.data("url");
var detail_info = {
post_title: form.find("#post_title").val(),
post_description: form.find("#post_description").val()
}
if(detail_info.post_title === "" || detail_info.post_description === "") {
alert("Fields cannot be blank");
return;
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
post_details : detail_info,
action: 'save_post_details_form' // this is going to be used inside wordpress functions.php// *esto se utilizará dentro de las functions.php*
},
error: function(error) {
alert("Insert Failed" + error);
},
success: function(response) {
modal.style.display = "block"; * abre la ventana modal*
body.style.position = "static";
body.style.height = "100%";
body.style.overflow = "hidden";
}
});
})
</script>
<button id="btnModal">Abrir modal</button>
<div id="tvesModal" class="modalContainer">
<div class="modal-content">
<span class="close">×</span> <h2>Modal</h2> * Ventana modal mostrar le url y ID generado *
<p><?php ***echo $title_post, $url, $ID*** ?></p>
</div>
</div>
Archive funtions.php
function save_enquiry_form_action() {
$post_title = $_POST['post_details']['post_title'];
$post_description = $_POST['post_details']['post_description'];
$args = [
'post_title'=> $post_title,
'post_content'=>$post_description,
'post_status'=> 'publish',
'post_type'=> 'post',
'show_in_rest' => true,
'post_date'=> get_the_date()
];
$is_post_inserted = wp_insert_post($args);
if($is_post_inserted) {
return "success";
} else {
return "failed";
}
}
When you use wp_insert_postDocs function, it'll return the post id.
It returns the post ID on success. The value 0 or WP_Error on failure.
First you could initiate an empty array and call it, let's say, $response and populate it based on the returned value from wp_insert_post function.
Then, we could use the id to get the permalink as well, using get_permalinkDocs.
And at last, we could send that array back to the client-side by using wp_send_json_successDocs function.
So your code on the php side would be something like this:
function save_enquiry_form_action() {
$response = array(
'error' => '',
'success' => '',
'post_id' => '',
'post_url' => '',
);
$post_title = sanitize_text_field($_POST['post_details']['post_title']);
// Note we could have used 'sanitize_title()' function too!
$post_description = sanitize_textarea_field($_POST['post_details']['post_description']);
$args = array(
'post_title' => $post_title,
'post_content' => $post_description,
'post_status' => 'publish',
'post_type' => 'post',
'show_in_rest' => true,
'post_date' => get_the_date()
);
$post_id = wp_insert_post($args);
if($post_id){
$response['success'] = true;
$response['error'] = false;
$response['id'] = $post_id;
$response['post_url'] = get_permalink($post_id);
}else{
$response['success'] = false;
$response['error'] = true;
}
wp_send_json_success($response);
exit;
}
Note:
I've used sanitize_text_fieldDocs function to sanitize the $_POST['post_details']['post_title'] value and sanitize_textarea_fieldDocs function to sanitize the $_POST['post_details']['post_description'] value.
When you receive the response on the client-side, you could check for $response['success'] and $response['error'] values.
On the javascript side
As you can see on the following screenshot, data returns as data object. To access data you could use response.data.success, response.data.error, response.data.id and response.data.post_url.

Uncaught (in promise) TypeError: result is null when using sweetalert for update confirmation

I have a update link that I need to do confirmation before it's go to update data. I've built using sweetalert in codeigniter.
The flow I want is if the user click ok, it will go to controller for update data, and if the user click cancel, it's not going anywhere.
However the data is not updated after user click Ok. And when I do console.log, is shows error like Uncaught (in promise) TypeError: result is null after I clicked cancel button.
Here's the html code
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<a title="Accept" href="<?= base_url(); ?>ControllerName/accept/<?= $j; ?>?id=<?= $id; ?>" onclick="confirmation(event)">
<button class="btn btn-blue1"><span class="fa fa-check"></span></button>
</a>
Here's the js code
function confirmation(event) {
event.preventDefault();
var urlToRedirect = event.currentTarget.getAttribute('href');
console.log(urlToRedirect); // verify if this is the right URL
swal({
text: "Are you sure you want to updated data ? ",
icon: "warning",
buttons: true,
dangerMode: true,
}).then((result) => {
if (result.isConfirmed) {
window.location.href=urlToRedirect;
}
else
{
Swal.fire(
'Deleted!',
'Your file has been deleted.',
'success'
)
}
});
}
Here's the controller code
$id = $this->input->get('id');
$data = array(
'status' => 'Accepted',
'updated_by' => $this->session->userdata('user_id')
);
$result = $this->Model->accept($data, $id);
This is model code
function accept($data, $id)
{
$this->db->where('id',$id);
if($this->db->update("schedule", $data)){
return true;
}else{
return false;
}
}
Do you know how to run this correctly ?
Thank you

How to use php for loop to create FilePond instances, and use plugins

I want to use a php for loop to create some file inputs with FilePond.
Each instance needs to have its own unique url, and use the plugins initiated. I have got the actual file uploads working, although the plugins don't seem to be getting used.
<?php
foreach ($objArray as $value) {
$inputNumber2++;
?>
<input name="input_<?= $inputNumber2; ?>_images[]" id="input_<?= $inputNumber2; ?>_images" class="filepond" type="files" multiple />
<script>
document.addEventListener('DOMContentLoaded', function() {
window['input<?= $inputNumber2; ?>Images'] = FilePond.create(
document.querySelector('#input_<?= $inputNumber2; ?>_images'),
{
server: {
url: '<?= Config::get('URL'); ?>',
process: 'upload/images/input_<?= $inputNumber2; ?>_images',
revert: 'upload/revert',
load: 'files/',
},
<?php
if (isset($value->imageArray) && count($value->imageArray) > 0) {
echo 'files: [';
foreach ($value->imageArray as $imageName) {
echo '{
source: "'.$imageName.'",
options: {
type: "local",
file: {
name: "'.$imageName.'",
type: "image/jpeg"
}
}
},';
}
echo '],';
}
?>
}
);
});
</script>
<?php } ?>
...
<script>
document.addEventListener('DOMContentLoaded', function() {
FilePond.registerPlugin(
FilePondPluginFileValidateType,
FilePondPluginImageExifOrientation,
FilePondPluginImagePreview,
FilePondPluginImageTransform,
FilePondPluginImageCrop,
FilePondPluginImageResize
);
FilePond.setOptions({
acceptedFileTypes: ['image/*'],
labelIdle: 'Add images or <span class="filepond--label-action"> Browse </span>',
imagePreviewMaxHeight: 100,
imagePreviewZoomFactor: 1,
});
});
</script>
I'm probably doing it wrong - how should I be doing it?
Also, it is picking up and using the custom label so some settings it is getting.
This line:
document.querySelector('#input_<?= $inputNumber2; ?>_images')
Returns a field with the id input_<?= $inputNumber2; ?>_images. But you've only assigned the name attribute to your input field. I suspect adding the id attribute to the input will solve the issue.
OR you can change the selector to:
document.querySelector('input[name="input_<?= $inputNumber2; ?>_images"]')

How to send multiple parameters in ajax call using post request in Yii2

I have a view in which I have a detailview and a gridview. In my grid view there are check-boxes against all the columns. The detail view contains the model id. Now the case is simple, I want to select any column from the grid view and then on click of the a link button I want to send the ajax call, which includes the value of selected column and the model id, to my controller. Below is my view
<?= GridView::widget([
'dataProvider' => $dataProvider,
/*'filterModel' => $searchModel,*/
'columns' => [
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['meter_id']];
}],
'Meter_Serial_Number',
'Issued_To',
'Store',
],
]); ?>
Set PDF
Now the javascript and the ajax call
<?php
$url = Url::toRoute(['/ogpheader/viewsetpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {
$('#myid').on('click',function() {
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
// alert(strValue);
$.ajax({
url: '$url',
type: 'POST',
data: {
data: strValue,// also tired with {strValue:strValue id:id} but it did not worked for me as well
},
success: function(data) {
alert(data);
},
});
})
});
JS;
$this->registerJs($script, static::POS_END);
?>
Action Controller
public function actionViewsetpdf($id)
{
$model = $this->findModel($id);
print_r($_POST);
$data = "";
if(Yii::$app->request->isAjax)
{
$data = json_decode($_POST['data']);
print_r($data);
}
else{
echo 'no data';
}
exit();
}
The response i always got is Array ( ) no data. I have also looked into Passing two parameters in yii2 ajax request using jquery to a controller and Yii2 extra parameter ajax in controller but both seems to be helpful in my case.
Note:
As per my understanding the id is a get and strValue is post. So I am confused in both of them. May be I am wrong.
Update 1
Image quality is not that good
The response in Xhr is
array(1) {
["data"]=>
array(1) {
["data"]=>
string(26) "99 , 100 , 101 , 102 , 103"
}
}
Any help would be highly appreciated.
Prevent the default click event
$('#myid').on('click',function(e) {
e.preventDefault();

$.post() data to Codeigniter 3

I have an $.post() and i want receive the data into my controller, how could i do that?
jQuery
$.post($('#url').val() + "Dashboard/getApi", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
vvvvvvvvvvvvvvvvvvv this is my url vvvvvvvvvvvvvv
$('#url').val() + "Dashboard/getApi" = "http://127.0.0.1/M2MWare/Dashboard/getApi"
And this is my controller
function getApi()
{
$valores = $this->input->post();
// print_r($valores);
return json_encode($valores);
}
this returns me an empty array, i tried with different url, data and nothing why?
Codeigniter 3.1.0 running on WampServer.
The Dashboard Controller
<?php
defined('BASEPATH') OR exit( 'No direct script access allowed' );
class Dashboard extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('post_view');
}
function getApi() {
$valores = $this->input->post();
echo json_encode($valores);
}
}
The View post_view.php This is Very Bare Bones for simplicity.
<html lang="en">
<head>
<title>Post Me</title>
</head>
<body>
<form>
<input type="hidden" id="url" value="http://ci310tut.com/">
</form>
<script src="<?= base_url('assets/js/jquery.min.js'); ?>"></script>
<script>
$(document).ready(function () {
console.log('We should be seeing an alert popup');
$.post($('#url').val() + "Dashboard/getApi", {name: "John", time: "2pm"})
.done(function (data) {
alert("Data Loaded: " + data);
});
});
</script>
</body>
</html>
And from the above I get an alert screaming at me each time I perform a page refresh with the provided data being displayed.
So you might want to check the above against what you have.

Categories