Show div element after reCaptcha validation - javascript

I am using Googles reCaptcha API for form validation.
I have opted to have the submit button show once the validation has been complete by using a little bit of JS.
<?php
if(isset($_POST['Login'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = '6LerNA0UAAAAAEReb9rS5JXjtvNSYlMjKiocUv_O';
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true){
//show submit button
echo '<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="visible";
}
</script>';
}
else{ // stay hidden
'<script type=\"text/javascript\">
function myFunction() {
document.getElementById("logDiv").style.visibility="hidden";
}
</script>';
}
}
?>
<div id='logDiv' style='visibility:hidden')
<?php
echo $form->add('Login',array('type' => 'submit'));
?>
</div>
Currently, the solution isn't working; when the Captcha is validated the div remains hidden.
Is this a result of a syntax error or have a made a logical error?
What is the bug in my code?
Are there any more robust solutions?

Why not simply use a php condition to show the div? I think your JS isnĀ“t working because you never call myFunction().
Try something like this but it will become complex over time and amount of code:
if(isset($data->success) AND $data->success==true){
$showButton = true;
}
......
if($showButton) { ?>
<div id='logDiv' style='visibility:hidden'
<?php echo $form->add('Login',array('type' => 'submit'));
?> </div> <?php }
......
Or a simple Solution:
if(is_bool($data -> success) && $data -> success){
echo '<div id="logDiv">'.$form->add('Login',array('type' => 'submit')).'</div>';
}
Echo the HTML Elements only if validition was successful otherwise simply dont ouput any HTML for the Div.
Hope this Helps.

Related

Insert an paragraph with jQuery in an PHP 'If' statement

I've written a simple login script that connects to a db, and now I want to insert a paragraph with jQuery in my #loginbox which says 'Login failed' when
if (!$row = mysqli_fetch_assoc($result))
is true.
My thought was:
[function.js]
function loginfailed() {
$('#loginbox').html("<p>Login failed.</p>");
}
[login.php]
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<?php
include '../config.php';
include 'dbh.php';
session_start();
$uid = $_POST['uid'];
$pw = $_POST['pw'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pw='$pw'";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php');
echo '<script> loginfailed(); </script>';
}
else
{
header('Location: ../index.php');
}
?>
But it doesn't work.
DON'T EVER STORE PASSWORDS IN PLAIN TEXT!!
Regarding your question.
The header function redirects to index.php and does not execute the echo. One solution can be to add a $_GET parameter and after the redirect check if it exists and echo the message or append it with JS.
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php?status=fail');
}
In the index.php file at the bottom (if you want to use JS/jQuery to show message)
<script>
var status = "<?php echo (!empty($_GET['status']) && $_GET['status'] === 'fail') ? 0 : 1; ?>";
if(!status) loginfailed();
</script>
Thanks guys, but i've found my own solution with the help of Allkin.
My header now redirects to
header('Location: ../index.php?status=fail');
and my #loginbox checks if status is set and then executes my loginfailed() function.
if(isset($_GET['status'])) {
echo '<script> loginfailed(); </script>';
}
Nothing easy like that!
Thanks for your help everyone.

append PHP code to HTML input placeholder?

I want to append a PHP function that shows the user his/her IP within an inputs' placeholder. I've never seen anything like this been done before so I'd like to just see if it's possible or not.
My thoughts right now is to do something along these lines:
$('input').attr(placeholder,function(){
$('input').append('<?php $variable ?>');
});
then run the PHP code through here some how. If someone can shed some light on this I would be very grateful!
try this:
$('#inputID').attr("placeholder","<?php echo $variable; ?>");
And if you want to append to all inputs:
$(":input").attr("placeholder","<?php echo $variable; ?>");
should do the work
If you want to do it in PHP you can make a function to retrieve the IP of the user then echo the script in your page:
<?PHP
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
echo "<script type='text/javascript'>
$('input').attr(placeholder,function(){
$('input').append('".getUserIP()."');
});
</script>";
?>

Alert box in PHP - Making me crazy

I know this question is very common, I have search alot, and after alot of hard work, I am asking here.
I simply want to show an alert box and redirect it to a page.
The code below is redirecting me, but not showing me the alert box.
Please, let me know my mistake.
<?php
require_once('connection.php');
if(isset($_POST['person'])){ $name = $_POST['person']; }
if(isset($_POST['pwd'])){ $password = $_POST['pwd']; }
if(isset($_POST['position'])){ $pos = $_POST['position']; }
if(empty($name) or empty($password))
{
echo "<SCRIPT type='text/javascript'>
alert('Places should not be empty! Press Ok and try again!');
window.location.replace(\"addmember.php\");
</SCRIPT>";
}
else
{
//$query=mysqli_query($con,"insert into members (username, password,position) values ('$name','$password','$pos')");
echo "<SCRIPT type='text/javascript'>
alert('Added!');
window.location.replace(\"addmember.php\");
</SCRIPT>";
}
?>
I personally make this function to show an alert box and redirect it to a page.
function do_alert($msg,$link=NULL)
{
echo '<script type="text/javascript">
alert("' . $msg . '");
</script>';
if(!empty($link)) {
echo '<script type="text/javascript">
window.location="'.$link.'";
</script>';
}
}
Use this function both alert and redirect to a page use this
do_alert("Message","URL");
do_alert("Here this is your alert","addmember.php");
do_alert("Only your alert");
If the function 2nd parameter URL is empty then it'll only do alert.
try to change
window.location.replace(\"addmember.php\");
to
window.location='addmember.php';

PHP isset variable than jquery and javascript should work

I want to know if my php variable does not exists, then I want to execute my javascript.
For example-
<?php
if(!isset($_REQUEST['myVar'])){
?>
<script>
alert('variable not exist');
</script>
<?php
}
?>
Is this right way to use javascript code in php extension file
I know all other answers solve your issue but i prefer it to do this way
<script>
<?php
$isset = !isset($_POST['myVar']) ? 'true' : 'false';
echo "var isset = $isset;";
?>
if(isset) {
alert('variable not exist');
}
</script>
when php render your page it will give this output
<script>
var isset = true;
if(isset) {
alert('variable not exist');
}
</script>
Do it like this and it will work:
if (!isset($_REQUEST['myVar'])) {
echo "<script>alert('variable not exist');</script>";
}
you can try writing this piece of code where you want the script to be placed:
<?php
if (!isset($_REQUEST['myVar'])) {
echo '<script>
alert("variable not exist");
</script>';
}
?>

How can I pass the name of the field in form_error ()

It's part of my view. Me need transmit input name in on which i click.
Below is a script that will get the name input after click
<div class="form_hint"><?=form_error('this get value from javascript after click')?></div>
<?php echo form_open("onenews/" . $onenews['id'] . "#signup", $form_reg['main_form']); ?>
<?php echo form_input($form_reg['login'], $this->form_validation->set_value('login')) ?>
<?php echo form_input($form_reg['email'], $this->form_validation->set_value('email')) ?>
<?php echo form_input($form_reg['password']) ?>
<?php echo form_input($form_reg['conf_password']) ?>
<?= MY_Controller:: create_captcha(); ?>
<?php echo form_input($form_reg['captcha']) ?>
<?php echo form_input($form_reg['submit']) ?>
<?php echo form_close(); ?>
</div>
</div>
jq
<script type="text/javascript">
$(function(){
var curInput = '';
$('#form_reg').find('input').on('click', function(){
curInput = $(this).attr("name");
});
})
</script>
Or i must use ajax?
Thanks!
Your question is not clear at all, but I assume you want to dynamically change the content of the form_hint div. You can't do that with PHP. Once PHP renders the page, it shuts down and does nothing more. So the only way to make PHP show that message is after the form submit, but then you lose your click data. There is a way to save the clicked element in a session for example, but that would be a really bad solution.
So the best solution would probably be to list all the hints in a JavaScript variable, and call the appropriate one upon the click event, and fill the form_hint div with it.
$('.form_hint').text(yourAppropriateMessageHere);
An example with a hidden div for the login input field with exactly how you described would be:
<div class="form_text_login"><?=form_error('login')?></div>
JS
var loginMessage = $('.form_text_login').text();
// list others here
// then make a tree with switch/case or if/else
if (curInput == 'login') {
$('.form_hint').text(loginMessage);
}
else if (curInput == 'email') {
// do the same with the email message, etc.
}

Categories