How to jQuery Validate the ReCaptcha? - php

Recaptcha form is like this:
<script type="text/javascript">
var RecaptchaOptions = {"theme":"red","lang":"en"};
</script><script type="text/javascript" src="https://www.google.com/recaptcha/api/challenge?k=6LeThAsTAAAAAKYRjSpA8XZ1s4izK65hYr9ulCiD">
</script><noscript>
<iframe src="https://www.google.com/recaptcha/api/noscript?k=6LeThAsTAAAAAKYRjSpA8XZ1s4izK65hYr9ulCiD"
height="300" width="500" frameborder="0"> </iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>
and validator of ZF2 for ReCaptcha is like this:
$recaptcha = new ZendService\ReCaptcha\ReCaptcha(PUB_KEY, PRIV_KEY);
$html = $recaptcha->getHTML();
$result = $recaptcha->verify($_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
if (!$result->isValid()) {
// invalid
} else {
// valid
}
is it possible to validate it remotely like this: https://jqueryvalidation.org/remote-method
I tried below in remote php file and it doesn't work:
$recaptcha = new ZendService\ReCaptcha\ReCaptcha(PUB_KEY, PRIV_KEY);
$result = $recaptcha->verify($_GET['recaptcha_challenge_field'], $_GET['recaptcha_response_field']);
if (!$result->isValid()) {
echo json_encode(false);
} else {
echo json_encode(true);
}
and js itself is:
$().ready(function() {
$("#contact").validate({
rules: {
recaptcha_response_field: {
required: true,
remote: "json.php"
}
}
});
});
is it possible at all or I did something wrong?

try this function to validate recaptcha
var grecaptchaId;
var onloadCallback = function () {
grecaptchaId = grecaptcha.render('grecaptcha', {
'sitekey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'callback': function (response) {
$("#grecaptcha_error").text('');
}
});
};
function ValidateRecaptcha() {
var x;
x = grecaptcha.getResponse(grecaptchaId);
if (x != "") {
$("#grecaptcha_error").text('');
return true;
}
else {
$("#grecaptcha_error").text('The captcha is required and can\'t be empty');
return false;
}
}

Related

Ajax + PHP validation and call Javascript function inside PHP validation

Basically, I'm trying to call a Javascript function inside a PHP script when using Ajax.
JavaScript:
<script type="text/javascript">
function Validate() {
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function() {
if ( hr.readyState == 4 && hr.status == 200 ) {
document.getElementById('message').innerHTML = hr.responseText;
}
}
hr.send('name=' + name);
}
function disable() {
document.getElementById('message').innerHTML = '';
}
</script>
HTML:
<div id="message"></div>
Name: <input type="text" id="name /">
<input type="button" onclick="Validate();" value="Validate" />
PHP:
<?php
$name = $_POST['name'];
if ( !empty( $name ) ) {
if ( $name == 'Tom' ) {
echo "<script>alert('Hello Tom, Welcome Back')</script>";
} else {
echo 'You are not Tom';
}
} else {
echo 'Please enter a name.';
}
?>
Everything works fine except calling the Javascript function inside PHP echo <script>alert()</script>
What I think the problem here is because I declared hr.responseText, as a result, the javascript I want to show has returned into text. But what should I do to solve this problem?
Any help would be appreciated.
Try changing your echo from "<script>alert('Hello Tom, Welcome Back')</script>";
to just 'Hello Tom, Welcome Back';
Then in your javascript you can call alert(hr.responseText);
You will have to change your javascript to check for what is returned so you know to call either the alert or the
document.getElementById('message').innerHTML = hr.responseText;
EDIT: I will add all the changed code...
<?php
$name = $_POST['name'];
if(!empty($name)){
if($name == 'Tom'){
echo 'Hello Tom, Welcome Back';
}else{
echo 'You are not Tom';
}
}else{
echo 'Please enter a name.';
}
?>
Javascript
<script type="text/javascript">
function Validate(){
hr = new XMLHttpRequest();
name = document.getElementById('name').value;
hr.open('POST', 'validator.php', true);
hr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
response = hr.responseText.replace(/^\s+|\s+$/g,''); //remove whitespace so you can compare
if (response == ("You are not Tom") || response == ("Please enter a name."))
{
document.getElementById('message').innerHTML = hr.responseText;
}
else {
alert(hr.responseText);
}
}
}
hr.send('name=' + name);
}
function disable(){
document.getElementById('message').innerHTML = '';
}
</script>
Try this:
function do_alert($msg){
echo '<script type="text/javascript">alert("' . $msg . '"); </script>';
}
if(!empty($name)){
if($name == 'Tom'){
do_alert("You are tom");
}else{
do_alert("You are not tom");
}
}else{
echo 'Please enter a name.';
}
You didn't tag jQuery, but if you are using it, $.getScript might be what you want.
Aside from that, it might be better to build the script into your original document, and then execute this or that function based on the response text.

Search data from array in php

I want to get data from php array and show it on same page. how to
import data from php array by using search box. This code not working properly.
What is th error of this code?
foodstore.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
} else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("cant create that object hoss!");
else
return xmlHttp;
}
function process(){
if(xmlHttp.readyState==0|| xmlHttp.readyState==4){
food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET","foodstore.php?food="+food,true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML ='<span style="color:blue">'+message+'</span>';
setTimeout('process',1000);
}else{
alert('Something went wrong!');
}
}
}
foodstore.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food,$foodArray))
echo 'We do have '.$food'!';
elseif($food =='')
echo 'Enter a food you want to buy';
else
echo 'Sorry we don't sell it '.$food'!';
echo '</response>';
?>
Index.html
<html><head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The foods </h3>
Order your foods:
<input type="text" id="Userinput"></input>
<div id="underInput"></div>
</body>
</html>
How to show array data by searching from search box
I have changed the code using jquery its simple . You can try it.
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(function()
{
$("#Userinput").keyup(function()
{
process();
});
$("#Userinput").keydown(function()
{
process();
});
$("#Userinput").focus(function()
{
process();
});
$("#Userinput").change(function()
{
process();
});
});
function process() {
var input_food = $("#Userinput").val();
$.ajax({
type: "GET",
url: "foodstore.php",
data: {food: input_food},
success: function(message)
{
$("#underInput").html('<span style="color:blue">' + message + '</span>');
},
error: function()
{
$("#underInput").html('<span style="color:red">Some error occured</span>');
}
});
}
</script>
</head>
<body >
<h3>The foods </h3>
Order your foods:
<input type="text" id="Userinput" ></input>
<div id="underInput"></div>
</body>
</html>
foodstore.php
<?php
if (!empty($_GET['food']))
{
$food = $_GET['food'];
$foodArray = array('tuna', 'bacon', 'beef', 'loaf', 'ham');
if (in_array($food, $foodArray))
echo "We do have " . $food . "!";
elseif ($food == '')
echo "Enter a food you want to buy";
else
echo "Sorry we don't sell it " . $food . "!";
}
else
{
echo "Enter a food you want to buy";
}
?>
I think its simple if you know jquery .And there was a simple error in php you did't escape the extra single quotes in (don't) so I used double quotes for echo statements. Copy paste and tell if this is it what you want or not.Got any doubt ask.

JS form validation not working

I'm trying to validate some form fields using JS functions, but they don't seem to load or check the field when the submit button is clicked.
<html>
<body>
<?php require_once('logic.php'); ?>
<h1>Add new Region/Entity</h1>
<?php
if ($_POST['submitted']==1) {
echo $error;
}
?>
<form action="logic.php" method="post" name="registration" onSubmit="return formValidation();">
Region: <input type="text" name="region" value="<?php echo #$_POST['region']; ?>"><br>
Description: <br><textarea name="description" cols="50" rows="10"><?php echo #$_POST['description']; ?></textarea><br>
Remarks: <input type="text" name="remarks" value="<?php echo #$_POST['remarks']; ?>">
<input type="hidden" name="submitted" value="1"><br>
<input type="submit" value="Submit" onclick="">
And here's the JS:
<script type="text/javascript">
function formValidation() {
var region = document.registration.region;
var descr = document.registration.description;
var remarks = document.registration.remarks;
if(empty_validation()) {
if(reg_validation()) {
if(reg_letters()) {
if (desc_letters()) {
if (desc_validation()) {
}
}
}
}
}
return false;
}
function empty_validation() {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
function reg_validation() {
if (reg_len > 50) {
alert("Only 50 characters are allowed in the Region field");
region.focus();
return false;
}
return true;
}
function reg_letters() {
var letters = /^[A-Za-z]+$/;
if(region.value.match(letters)) {
return true;
} else {
alert('Region field must have only alphabetical characters');
region.focus();
return false;
}
}
function desc_validation() {
if (descr_len > 500) {
alert("Only 500 characters are allowed in the description field");
descr.focus();
return false;
}
return true;
}
function desc_letters() {
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < descr_len; i++) {
if (iChars.indexOf(descr.value.charAt(i)) != -1) {
alert ("Your description has special characters. \nThese are not allowed.\n Please remove them and try again.");
return false;
}
}
return true;
}
</script>
</form>
</body>
</html>
As you can see, I'm posting values from the form to a PHP file. And I've used the onSubmit event in the form tag to initialize the formValidation() function. It isn't working for some reason.
Here's a working example if you need one.
I'm not going to fix every little error you have, but the main problem is that variables aren't defined where you expect them to be. You can't declare a variable in one function and expect it to be available in the next (without passing it as a parameter or declaring it globally). For example, your empty_validation function should be this:
function empty_validation(region, descr, remarks) {
var reg_len = region.value.length;
var descr_len = descr.value.length;
var rem_len = remarks.value.length;
if (reg_len == 0 || decr_len == 0 || rem_len == 0) {
alert("Please fill all the fields");
return false;
}
return true;
}
And in your formValidation function, you call it like this:
if(empty_validation(region, descr, remarks)) {
This is just one example, and you would need to do it in a few places.
A few other things - you always return false from formValidation...did you mean to put return true; inside the innermost if statement? Also, since all you seem to be doing is calling each of those functions, you can probably put them into one big if statement, like this:
if (empty_validation() && reg_validation() && reg_letters() && desc_letters() && desc_validation()) {
return true;
}
return false;

validating and submitting with 'if' and 'else' using PHP

This code is supposed to check to see if any fields are blank or invalid, if they are, it will turn them red. if all is ok then it will send to the database.
The problem is, if the last 'if' is not met, then the 'else' will fire.
This means as long as a valid email address is entered the form will submit, even if other fields are blank.
How can I make so that all requirements must be met for the form to submit
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
}
else {
//submits to database...
}
You can use a flag as:
$isValid = true;
if(empty($_POST['company'])) {
$isValid = false;
// your echo
}
Similarly add the $isValid = false; for all the other if bodies.
Finally remove your else part and replace it with:
if($isValid) {
// submit to DB.
}
you either can use else if, but then you won't see your "red" for all wrong fields but only for the first that failed validation.
like so:
if() {
} elseif() {
} else {
...
}
or you could set something to $error=false at the beginning, and set error to true inside the if controlled code and the submission to database checks if error is still false...
<?php
$error = 1;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 0;
}
if($error == 1) { //submits to database...
}
?>
There is a far better way of doing this instead of repeating your own code for each POST variable, which is not efficient.
// loop through all submitted fields
foreach( $_POST as $key => $value){
// see if the field is blank
if($value=="" || $value is null){
// if blank output highlighting JS
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$key."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
// variable to value showing form is invalid in some way
$invalid=1;
}
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$invalid= 1;
}
// if form invalid variable not set, submit to DB
if($invalid!=1){
// submit to DB
}
If you want to be super efficient you can simply use:
// search for any values that are null (empty fields)
$invalid_fields=array_keys($_POST, null);
// you may need to use $invalid_fields=array_keys($_POST, "");
// if there are any results from this search, loop through each to highlight the field
if($invalid_fields){
foreach( $invalid_fields as $key => $value){
echo "<script type='text/javascript'>
$(document).ready(function() {
$('#".$value."Form').animate({backgroundColor:'#ffbfbf'},500);
});
</script>";
}
$error = 1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$error = 1;
}
if($error!=1){
// submit to DB
}
Introduce a Variable $sendToDb and initialy set it to (bool) true. If any of your checks fails, set this variable to false.
Then rewrite the else-Part and do a
if ($sendToDb) {
/* Your Db-Write code */
}
Take a flag variable and check like this
$flag=0;
if(empty($_POST['company'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#companyForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['name'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#nameForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(empty($_POST['email'])) {
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
echo '<script type="text/javascript">
$(document).ready(function() {
$("#emailForm").animate({backgroundColor:"#ffbfbf"},500);
});
</script>
';
$flag=1;
}
if ($flag == 0)
{//submit to database
}
You really shouldn't be mixing server-side code (PHP) with client-side code (JavaScript).
Validate on the server side first. Then add validation on the client side. The reason being, if your user has JavaScript enabled then they'll get the error messages before the form submits. If they have JavaScript disabled, then your PHP script will throw the errors. Something like the following script:
<?php
if (isset($_POST['submit'])) {
$errors = array();
// do server-side validation
if ($_POST['fieldName'] == '') {
$errors['fieldName'] = 'fieldName is required';
}
if (count($errors) == 0) {
// save your record to the database or whatever
}
}
And then the following template:
<style>
.error { border-color: red; }
</style>
<script>
$(document).ready(function() {
$('form#yourFormId').submit(function() {
var errors = null;
if (errors.length > 0) {
return false;
}
});
});
</script>
<form action="yourScript.php" method="post" id="yourFormId">
<input type="text" name="fieldName" value="" id="id"<?php if (in_array('fieldName', $errors)) echo ' class="error"'; ?>>
<input type="submit" name="submit">
</form>
This will apply a class of .error to any invalid form fields, first by JavaScript and then server-side.

keypressed() and onCLick() implementation problem in IE

I've the following input text box and a button.
<div id="sender" onKeyUp="keypressed(event);">
Your message: <input type="text" name="msg" size="70" id="msg" />
<button onClick="doWork();">Send</button>
</div>
The keypressed(event) function actually detects if the key being pressed is "Enter" and calls the doWork() function.
function keypressed(e){
if(e.keyCode=='13'){
doWork();
}
}
This code seems to work fine in Chrome & Firefox. But in IE, the function seems to called twice.
Can anyone help me tweak the code so that it works properly in IE also.
Thanks
EDITED:
Whole ajax codes
<!--
var httpObject = null;
var link = "";
var timerID = 0;
var nickName = "Unname"; //"<?php echo $nickname; ?>";
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Change the value of the outputText field
function setOutput(){
if(httpObject.readyState == 4){
var response = httpObject.responseText;
var objDiv = document.getElementById("result");
objDiv.innerHTML += response;
objDiv.scrollTop = objDiv.scrollHeight;
var inpObj = document.getElementById("msg");
inpObj.value = "";
inpObj.focus();
}
}
// Change the value of the outputText field
function setAll(){
if(httpObject.readyState == 4){
var response = httpObject.responseText;
var objDiv = document.getElementById("result");
objDiv.innerHTML = response;
objDiv.scrollTop = objDiv.scrollHeight;
}
}
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
link = "message.php?nick="+nickName+"&msg="+encodeURIComponent(document.getElementById('msg').value);
httpObject.open("GET", link , true);
httpObject.onreadystatechange = setOutput;
httpObject.send(null);
}
}
// Implement business logic
function doReload(){
httpObject = getHTTPObject();
var randomnumber=Math.floor(Math.random()*10000);
if (httpObject != null) {
link = "message.php?all=1&rnd="+randomnumber;
httpObject.open("GET", link , true);
httpObject.onreadystatechange = setAll;
httpObject.send(null);
}
}
function UpdateTimer() {
doReload();
timerID = setTimeout("UpdateTimer()", 5000);
}
function keypressed(e){
if(e.keyCode=='13'){
doWork();
}
}
//-->
If someone is facing a similar problem, this could be useful.
I solved the problem by detecting IE browser using PHP script and discarding the onKeyUp() function while rendering HTML for IE.
IE Detection PHP script
//Detect IE function
function detectIE() {
if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
return true;
else
return false;
}
And this is how i changed the event handling.
<div id="sender" <?php if (detectIE()) { /*do nothing */ } else { echo "onKeyUp=\"keypressed(event);\""; } ?> >
Your message: <input type="text" name="msg" size="70" id="msg" />
<button onClick="doWork();">Send</button>
</div>

Categories