how to get response of clicked captcha as a variable - php

I want to include google recaptcha in my login page.
Normally, I collect variables from various inputs and sent them using ajax to prologin.php for proccessing.
But don't know how to get response of clicked captcha, what kind of responses are possible (true, false, or... what ?), to proccess them also.
login.php
<script src='https://www.google.com/recaptcha/api.js'></script>
<input type='text'...>
<input type='checkbox'...>
<div class="g-recaptcha" data-sitekey="6Ld..."></div>
<div id='btnlogin'>LOGIN</div>
login.js
$('#btnlogin').click(function(){
var a = ...;
var b = ...;
var captchaResponse = ...; // what ?
$.ajax({
url: 'prologin.php',
...
});
Any help?

You have to use grecaptcha.getResponse() to get the user's response. And as a sidenote, use grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
$('#btnlogin').click(function(){
var a = ...;
var b = ...;
var captchaResponse = grecaptcha.getResponse();
$.ajax({
url: 'prologin.php',
...
});
...
});
Here's the reference: https://developers.google.com/recaptcha/docs/verify
Update(1): Yes, you have to send user's response to backend PHP page prologin.php and get it verified there. So roughly, your AJAX and backend PHP code would be like this:
AJAX:
$('#btnlogin').click(function(){
var a = ...;
var b = ...;
var captchaResponse = grecaptcha.getResponse();
$.ajax({
type: 'POST',
url: 'prologin.php',
data: {a: a, b: b, captchaResponse: captchaResponse};
success: function(data) {
// reset the reCaptcha
grecaptcha.reset();
},
error: function(jqXHR, textStatus, errorThrown){
// error
}
});
...
});
prologin.php
<?php
//your site secret key
$secret = 'YOUR_SECRET_KEY';
if(isset($_POST['captchaResponse']) && !empty($_POST['captchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['captchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
}else{
// failure
}
}
?>

Google recaptcha's response is sent with name g-recaptcha-response. This is also class name and ID for an input (textarea). So you can try any of these:
$('#g-recaptcha-response').val();
$('form .g-recaptcha-response').val();
$('form [name="g-recaptcha-response"]').val();

Related

Load() not working to call a PHP template when submitting a form

I'm trying to load a php file into a div on submission of a form. At the moment everything fires bar this line $('#signupform').load('newsletter-signup-call.php');, I've just got a simple echo request in there and it doesn't fire. If I goto that template it works though.
Where am I going wrong? Could I possibly fire two Ajax calls (as that in itself works) but there seems to be issues with load.
<script>
$("#signupForm").submit(function(e) {
e.preventDefault();
var form = $(this);
var email = $("#EmailAddress").val();
$.ajax({
type: "POST",
url: form.attr('action') + '?email=' + email,
data: form.serialize(),
beforeSend: function(){
$(".newsletter-loading").show().css({"display":"inline-block"});
},
success: function(data)
{
console.log(data); //data contain response from your php script
register_signup();
register_prefs();
(function() {
window.sib = {
equeue: [],
client_key: "xxx"
};
/* OPTIONAL: email for identify request*/
window.sib.email_id = email;
window.sendinblue = {};
for (var j = ['track', 'identify', 'trackLink', 'page'], i = 0; i < j.length; i++) {
(function(k) {
window.sendinblue[k] = function() {
var arg = Array.prototype.slice.call(arguments);
(window.sib[k] || function() {
var t = {};
t[k] = arg;
window.sib.equeue.push(t);
})(arg[0], arg[1], arg[2]);
};
})(j[i]);
}
var n = document.createElement("script"),
i = document.getElementsByTagName("script")[0];
n.type = "text/javascript", n.id = "sendinblue-js", n.async = !0, n.src = "https://sibautomation.com/sa.js?key=" + window.sib.client_key, i.parentNode.insertBefore(n, i), window.sendinblue.page();
})();
sendinblue.track('marketing');
$(".newsletter-loading").hide();
form.replaceWith("<br /><p>Thanks for signing up! You'll receive an email with your discount.</p>");
}
});
});
function register_prefs(){
var email = $("#EmailAddress").val();
Cookies.set('Address', email, { expires: 100000 });
$('#signupform').load('newsletter-signup-call.php');
}
function register_signup(){
ga( 'send', 'event', 'Newsletter Sign Up', 'submit' );
}
</script>
Try to console.log the response status to see what's going wrong
function register_prefs(){
//see if this function is triggered
console.log('register_prefs function triggered')
var email = $("#EmailAddress").val();
Cookies.set('Address', email, { expires: 100000 });
$('#signupform').load('newsletter-signup-call.php', function( response, status, xhr ){
console.log('Server response : ', response)//The serve response
console.log('Status Message : ', [xhr.status, xhr.statusText])//See the status of your request, if any error it should be displayed here
});
}
BUT, Why perform another server call with load, when your are already using ajax, you can return the html in the first call in a json object {Mydata: ..., MyHTML: ...} and just use $('#signupform').html(data.MyHTML) on success.
Also, not sure but I'm suspecting a malformed URL, try this instead '/newsletter-signup-call.php' or an absolute path just to be sure.

how to post a persian statement with spaces in ajax url

I have used ajax as below:
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var valueSelected = valueSelected.replace(/ /gi,"%20");
var valueSelected = encodeURIComponent(valueSelected);
//alert(valueSelected);
$.ajax({
type: 'post',
encoding:"UTF-8",
url: "<?php echo base_url();?>Search/cities_of_province/"+valueSelected,
data: '',
contentType: "charset=utf-8",
success: function (result) {
//alert(result);
$('.city').html(result);
return false;
}
});
return false;
});
valueSelected in above url is a persion statement with space in it. for example it is استان آذربایجان شرقی.
when it is post to the url, just first part(استان) is recieved.
I aslo removed valueSelected.replace(/ /gi,"%20") and encodeURIComponent(valueSelected) but nothing happend.
what is the solution?
I faced no issue like that.. I used no encodeURIComponent no encoding:"UTF-8" no contentType: "charset=utf-8"
Nothing needed. And it works simply perfect. I tested it with following code
I have Html
<input id='yourInputId' value='استان آذربایجان شرقی' />
JavaScript
<script>
var valueSelected = $('#yourInputId').val();
//before ajax request
alert(valueSelected ); // it gives me here =>استان آذربایجان شرقی
//before making ajax reuest plz confirm you get above value correctly here
alert(<?php echo base_url();?>); //it must be valid as well
$.ajax
({
type: "POST",
url: "<?php echo base_url();?>Search/cities_of_province", //should be valid
data: { province : valueSelected },
success: function (result) {
alert(result); //it gives => استان آذربایجان شرقی
},
error:function(a)
{
alert(a.responseText);
}
});
</script>
PHP
<?php
if(isset($_POST['province']))
$v = $_POST['province'];
else
$v = 'Province value not provided from client side';
echo $v;
?>
So it looks like you are using a select input here. If that is the case, you should use alphanumeric/ASCII value key in your options and not the human readable labels. That might look like:
<option value="some_ascii_key">استان آذربایجان شرقی</option>
You can then have a reliable key to use in your AJAX request.
I also think your request should be a GET and not a POST since you are just reading values from API rather than trying to create/update records via API.
Putting it all together, you might have something like this:
// note values for each property/ley may not be important here
// as they are not really needed to validate that the province key
// in option value has not been modified by client,
// which is really what you are using this for.
// If you need to have option label text available in
// javascript you can store that here as shown.
var provinceConfiguration = {
'key1': 'استان آذربایجان شرق';
'key2': 'some other Persian string';
// and so on...
}
$('.province').on('click', function (e)
{
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
// perhaps validate that value provided is amongst expected keys
// this used the provinceConfiguration object proposed in this example
if(typeof provinceConfiguration[valueSelected] === 'undefined') {
console.log('Unexpected province key passed');
e.stopPropagation();
return false;
}
// probably can drop this line if defined keys do not need encoding
var valueSelected = encodeURIComponent(valueSelected);
// since you can use default GET setting you can use this shorthand
$.get(
'<?php echo base_url();>Search/cities_of_province/' +
valueSelected,
function(result) {
// console.log(result);
$('.city').html(result);
return false;
}
);
/*
Or more verbose option
$.ajax({
type: 'GET',
// not valid setting key -> encoding:"UTF-8",
url: '<?php echo base_url();>Search/cities_of_province/' + valueSelected,
// default is fine here so not needed -> contentType: "charset=utf-8",
success: function (result) {
// console.log(result);
$('.city').html(result);
return false;
}
});
*/
return false;
});
Note that you should be using console.log() to debug code rather than alert(), as alert actually blocks code execution and may make some debugging more problematic as your debugging mechanism changes how your code executes. This can problem can be exacerbated when debugging asynchronous code.
Your server-side code would obviously need to be updated to understand the province keys as well.
Please take a look at this javascript library. That can be of help to you.
Fix Persian zero-width non-joiner(Replace spaces by half-space)
import { halfSpace } from "persian-tools2";
halfSpace("نمی ‌خواهی درخت ها را ببینیم؟") // "نمی‌خواهی درخت‌ها را ببینیم؟"
Fix Persian characters in URL.
import { isPersian, toPersianChars } from "persian-tools2";
URLfix(
"https://fa.wikipedia.org/wiki/%D9%85%D8%AF%DB%8C%D8%A7%D9%88%DB%8C%DA%A9%DB%8C:Gadget-Extra-Editbuttons-botworks.js",
); // "https://fa.wikipedia.org/wiki/مدیاویکی:Gadget-Extra-Editbuttons-botworks.js"
URLfix("https://en.wikipedia.org/wiki/Persian_alphabet"); // "https://en.wikipedia.org/wiki/Persian_alphabet",
URLfix("Sample Text"); // "Sample Text"

passing return variable from ajax to php

this is my ajax code that work perfectly if i show using an id.
$("#masa").change(function()
{ //if theres a change in the nokakitangan textbox
var masa = $("#masa").val();
var tkh_kerja = $("#tkh_kerja").val();
//Get the value in the nokakitangan textbox
if(tkh_kerja=='')
{
$("#cek_tarikh").html('<font color="Red"> Sila Isi Maklumat Tarikh Mula Bekerja </font>');
}
else
{
$("#cek_tarikh").html('<align="absmiddle"> Cek Tarikh Akhir...');
$.ajax
({ //Make the Ajax Request
type: "POST",
url: "ajax_cek_tarikhakhir.php", //file name
data: "bulan="+ masa +"&tkh_kerja="+tkh_kerja, //data
success: function(cekmasa)
{
$("#cek_tarikh").ajaxComplete(function(event, request)
{
$("#cek_tarikh").val(cekmasa);
});
}
});
}
return false;
});
the problem is, can the 'cekmasa' value pass to the php.? i need to use that value to do some code in php. is it possible to get the data from ajax? in the same page.
there is no problem when i return value in
<input align='right' type="text" name="tkh_akhir" maxlength="3" id="cek_tarikh" class="span2" readonly/>
no, that's not possible.
once your PHP page is processed by the server it sends the generated output to the client. and there is no PHP executed unless you reload the page or go to another page in your browser.
additional information: that's what often gets confused by people that start working with ajax. you use ajax because you want some "realtime behavior" without having to reload a whole html page. but ajax still is executed by your browser on the clientside.
simplified that's what you want to achieve with ajax, a communication between your browser and the server:
client(browser) <- ajax -> server(PHP)
but what you are asking for would be something like this:
server(PHP) <- ajax -> server(PHP)
which doesn't work and doesn't really make sense if you think about it.
you can call another ajax function to use php file inside success response like below
$("#masa").change(function()
{ //if theres a change in the nokakitangan textbox
var masa = $("#masa").val();
var tkh_kerja = $("#tkh_kerja").val();
//Get the value in the nokakitangan textbox
if(tkh_kerja=='')
{
$("#cek_tarikh").html('<font color="Red"> Sila Isi Maklumat Tarikh Mula Bekerja </font>');
}
else
{
$("#cek_tarikh").html('<align="absmiddle"> Cek Tarikh Akhir...');
$.ajax
({ //Make the Ajax Request
type: "POST",
url: "ajax_cek_tarikhakhir.php", //file name
data:
{
bulan:masa,
tkh_kerja:tkh_kerja
}, //data
success: function(cekmasa)
{
$("#cek_tarikh").ajaxComplete(function(event, request)
{
$("#cek_tarikh").val(cekmasa);
$.ajax
({ //Make another Ajax Request
type: "POST",
url: "", //file name
data:
{
}, //data
success: function()
{
}
});
});
}
});
}
return false;
});
You can do one thing. You can store ajax response in php session or cookie and then simply refresh page on ajax response.
//File: ajax_cek_tarikhakhir.php
// Your ajax handling code.
if(isset($__SESSION('ckmasa')){
$ckmasa = $__SESSION('ckmasa');
// use this $ckmasa for your php
}
$ckmasa = $output; // $ckmasa have data which you send to ajax response.
$__SESSION['ckmasa'] = $ckmasa;
echo $ckmasa;
return;
For your jQuery. Do as following.
$("#masa").change(function()
{ //if theres a change in the nokakitangan textbox
var masa = $("#masa").val();
var tkh_kerja = $("#tkh_kerja").val();
//Get the value in the nokakitangan textbox
if(tkh_kerja=='')
{
$("#cek_tarikh").html('<font color="Red"> Sila Isi Maklumat Tarikh Mula Bekerja </font>');
}
else
{
$("#cek_tarikh").html('<align="absmiddle"> Cek Tarikh Akhir...');
$.ajax
({ //Make the Ajax Request
type: "POST",
url: "ajax_cek_tarikhakhir.php", //file name
data: "bulan="+ masa +"&tkh_kerja="+tkh_kerja, //data
success: function(cekmasa)
{
$("#cek_tarikh").ajaxComplete(function(event, request)
{
$("#cek_tarikh").val(cekmasa);
// Reload page
location.reload();
});
}
});
}
return false;
});
I have just reloaded your page on ajax response. I have no idea how your server side code. but i tried to give some brief. hope this helps you. I have not tested code written above. Sorry for my bad English.

Update database phone number

Currently my running program, when I click the submit new phone number button, my ajax shows a response pop up that is empty.
I don't have any running errors so I don't see the issue.
main index.php file:
case 'updatephone' :
include('assets/header.php'); // create top box
include('assets/sidemenu.php'); // create side menu
// use a template to display result
include('views/displayUpdatePhoneForm.php');
include('assets/footer.php'); // create footer
break;
case 'changephone' :
$sql = 'update members set mobilePhone=:mobilePhone where indID=:indID';
$phone = $_POST['mobilePhone'];
$values = array(':indID'=>$_POST['indID'], ':mobilePhone'=>$phone);
$stm = $db->prepare($sql);
$result = $stm->execute($values);
echo $result;
break;
displayUpdatePhoneForm.php
<h4>Changing Mobile Phone</h4>
<p>Enter new number: <input type='tel' id='newPhone' />
<button type='button' class='btn btn-primary' id='updatephone' >Change Phone</button>
</p>
script.js
$(document).ready(function(){
url = '/cs382/cookead06/final/final_app';
if ($('#uid').val() != '-1'){
$('#sign-in' ).hide();
$('#sign-out').show();
}
$('#p2').on('change', function(){
$('#form2').submit();
});
$('#p3').on('change', function(){
$('#form3').submit();
});
$('#p4').on('change', function(){
$('#form4').submit();
});
// validate user
$('#updatephone').on('click', function(){
var f_id = $('#uid').val();
var phone = $('#newPhone').val();
$.ajax({
type : 'post',
url : url + '/index.php?action=changephone',
data : 'indID=' + f_id + '&mobilePhone='+ phone,
success : function(response){
alert(response);
}
});
});
$('#signInBtn').on('click', function(){
var username = $('#username').val();
var password = $('#passwd').val();
var data_items = 'username='+username + '&passwd=' + password;
$.ajax({
type : 'post', // type: get or post
url : url + '/index.php?action=checklogin', // define server-side script
data : data_items, // define data to be sent
success : function(response){
if (response != -1){
// hide login information
$('#username, #passwd').val('');
$('#login-content, #sign-in').hide();
$('#sign-out').show();
// update the value of 'uid'
$('#uid').val(1);
// display user's name
$('#user-info').text(response);
$('#update-link').removeClass('hidelink').addClass('displaylink');
} else
alert("Invalid user");
}
});
});
});
Sorry, read wrongly..
I re-read it and I can see that you are printing $result that is = to $stm->execute($values); that is a sql query, if the query executes successfully, it won't show any message, only if you implemented an echo on the function execute..
Surprisingly, the issue was at line:
$sql = 'update members set mobilePhone=:mobilePhone where indID=:indID';
where members was suppose to cs_members(name of table)

jquery .load() and wordpress usability

I'm working on wordpress theme, you can take a look at: greenzoner.pl. What I want to do is showing all posts usability in the middle div, i.e single posts, comments, attached pictures etc. 2 side divs should never reload. I am open to any alternatives to method I try to use (maybe IFRAME?).
To load sigle post I used jquery .load()
$.ajaxSetup({ cache: false });
$(".openpost, .comments-link").click(function() {
var post_url = $(this).attr("href");
$(".container").load(post_url);
return false;
});
$(".closepost").click(function() {
$(".container").load(index.php .postlist);
return false;
});
I've encountered a major problem - I cant use ajax comments ( i tried many plugins, tutorials, etc, nothing works) - so basicly when you post reply, you get redirected to eg. http://greenzoner.pl/?p=32#comment-26. My current js for comments is:
var commentform = $('#commentform'); // find the comment form
commentform.prepend('<div id="comment-status" ></div>'); // add info panel before the form to provide feedback or errors
var statusdiv = $('#comment-status'); // define the infopanel
commentform.submit(function(){
//serialize and store form data in a variable
var formdata = commentform.serialize();
//Add a status message
statusdiv.html('<p>Processing...</p>');
//Extract action URL from commentform
var formurl = commentform.attr('action');
//Post Form with data
$.ajax({
type: 'post',
url: formurl,
data: formdata,
error: function(XMLHttpRequest, textStatus, errorThrown) {
statusdiv.html('<p class="wdpajax-error" >You might have left one of the fields blank, or be posting too quickly</p>');
},
success: function(data, textStatus) {
if (data == "success")
statusdiv.html('<p class="ajax-success" >Thanks for your comment. We appreciate your response.</p>');
else
statusdiv.html('<p class="ajax-error" >Please wait a while before posting your next comment</p>');
commentform.find('textarea[name=comment]').val('');
}
});
});
and php:
add_action('comment_post', 'ajaxify_comments',20, 2);
function ajaxify_comments($comment_ID, $comment_status) {
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
//If AJAX Request Then
switch($comment_status){
case '0':
//notify moderator of unapproved comment
wp_notify_moderator($comment_ID);
case '1': //Approved comment
echo "success";
$commentdata = &get_comment($comment_ID, ARRAY_A);
$post = &get_post($commentdata['comment_post_ID']);
wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
break;
default:
echo "error";
}
exit;
}
}
Other problem with using this method, is post linking.

Categories