php jquery remote validate problem - php

<script type="text/javascript">
$().ready(function() {
jQuery.validator.addMethod("captcha", function(value, element) {
$.ajax({ url: "verifyCap.php",
type: "GET",
data: "txtCaptcha="+value,
success:
function(msg) {
if(msg == "true")
return true; // already exists
return false;
}
});
},"");
// validate signup form on keyup and submit
$("#signupForm").validate({
rules: {
title: "required",
contactname: "required",
email: {
required: true,
email: true
},
comment: "required",
txtCaptcha:{
required: true,
captcha: true
}
},
messages: {
contactname: "Please enter your contact name",
email: "Please enter a valid email address",
comment: "Please enter your system requierment",
txtCaptcha: {
required:"Please enter verification code",
captcha: "The verification code is incorrect"
}
}
});
});
My verifyCap.php
<?php
session_start ();
if ($_SERVER ["REQUEST_METHOD"] != "GET")
die ( "You can only reach this page by posting from the html form" );
if (($_GET ["txtCaptcha"] == $_SESSION ["security_code"]) && (! empty ( $_GET ["txtCaptcha"] ) && ! empty ( $_SESSION ["security_code"] ))) {
echo "true";
} else {
echo "false";
}
?>
My problem might due to the response format it is not true or false, but i print out whole verifyCap code. Anyone can help?

An ajax request does an get by default instead of a post. Change:
if ($_SERVER ["REQUEST_METHOD"] != "POST")
to
if ($_SERVER ["REQUEST_METHOD"] != "GET")
besides that, do not use $_REQUEST to get your data. Use $_GET instead.
You could also add some settings your ajax request:
type: "POST",
data: "your params here",

You're receiving the whole verifyCap.php code because your PHP isn't interpreted by your web server.
In your verifyCap.php you are using the short tag notation (<? //code ?>).
Not all server uses this php extension, and it is considered deprecated. If your webserver doesn't use this extension, then your code is considered as an XML document, as XML document always start with <? <!-- some XML here --> ?>.
Use <?php //code ?> and your problem should be fixed.
Also, following #XpertEase answer isn't a bad idea either.
Edit: More info on PHP short tags Are PHP short tags acceptable to use? (via #XpertEase)

Related

Jquery remote method showing the email and mobile already exist on the edit page without change anything

I am using CodeIgniter with jQuery validation. I am using remote to check mobile number and email id is already available or not in the database. So there is no issue when the user registers. I am getting the issue on the edit page.
On the edit page, I just change the name and address but mobile number and email id both are showing already exist. I haven't change mobile and email. I know it will call the controller to check mobile and email are available or not but is there any other way to handle this issue?
I mean, not to check the previous data and check current data if the user enters anything in the field.
I want to check user against the database when creating the account, but NOT check user against the database when editing the account.
$("#edit_member").validate({
errorElement: 'div',
rules: {
name: {
required: true,
alphabets: true,
minlength: 3
},
email: {
required: true,
Email: true,
remote: {
url: baseUrl + "/AddMember/isEmail",
}
},
phone: {
required: true,
number: true,
minlength: 10,
maxlength: 10,
remote: {
url: baseUrl + "/AddMember/isMobile",
// async: false
}
},
address: {
required: true,
minlength: 10
}
},
messages: {
email: {
remote: "Email already Exists"
},
phone: {
remote: "Mobile no already Exists"
},
},
submitHandler: function(form) {//form.submit();}
});
Controller
function isEmail()
{
$email = trim($this->input->get('email'));
$result = $this->addmember_model->isEmail($email);
if($result)
{
echo $msg = "false";
}
else
{
echo $msg = "true";
}
}
function isMobile()
{
$mobile = trim($this->input->get('phone'));
$result = $this->addmember_model->isMobile($mobile);
if($result)
{
echo $msg = "false";
}
else
{
echo $msg = "true";
}
}
Model
function isEmail($email)
{
$result = $this->db->where(['email'=>$email,'is_status'=>1])
->get('members')
->row();
return $result;
}
function isMobile($mobile)
{
$result = $this->db->where(['phone'=>$mobile,'is_status'=>1])
->get('members')
->row();
return $result;
}
Use PHP to determine if the page is Editing or Creating and set a variable as such. You could look at a URL segment with the URI Class.
<?php
$create = ($this->uri->segment(3) == "create") ? TRUE : FALSE;
?>
Then use PHP to write the relevant rule(s) for that particular version of the View.
$("#edit_member").validate({
....
rules: {
....
email: {
required: true,
Email: true,
<?php if ($create) : ?>
remote: {
url: baseUrl + "/AddMember/isEmail",
}
<?php endif; ?>
},
....
The above only works when this part of the JavaScript is in the View file and not included from an external JavaScript file.
Otherwise, if .validate() is part of an externally included JavaScript file, then you can use the .rules() method instead.
After the JavaScript includes (after .validate() invoked), programmatically remove the remote rule.
<?php if ($edit) : ?>
<script>
$(document).ready(function() {
$('[name="email"]').rules('remove', 'remote');
});
</script>
<?php endif; ?>

Remote validation in jquery validation not returning

I have tried to get this to work and have been unsuccessful, I have tried 18 different ways all produced the same result. I have double checked and triple check everything. NOTHING HAS WORKED! I have validation done server side as a fall back if jquery does not work. the validation part works fine its the cheeking if exists that is not working required is working.
My form field
<div class="col-sm-12">
<label>Name</label>
<input type="text" class="form-control" autocomplete="off" name="name" id="name" value="<?php echo isset($_POST['name']) ? $_POST['name'] : '' ?>">
</div>
My jquery vaidate function
$(function() {
$("form[name='register']").validate({
rules: {
name: {
required: true,
name: true,
remote: {
url: "../includes/check.php",
type: "post",
data: {
name: function() {
return $( "#name" ).val();
}
}
}
},
email: {
required: true,
email: true
},
password: {
required: true,
minlength: 5
}
},
messages: {
name: {
required: "Please enter your name",
minlength: "Name must be at least 4 characters long",
remote: "The name entered is unavailable"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
email: "Please enter a valid email address"
},
submitHandler: function(form) {
form.submit();
}
});
});
My query script
include("db.php");
if(isset($_POST['name'])) {
$name = $_POST['name'];
$db = dbconnect();
$stmt = $db->prepare("SELECT Name FROM users WHERE Name = ?");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1){
echo 'true';
}else{
echo 'false';
}
}
The problem is not directly related to the remote validation.
You just need to remove
name: true,
from your validation options. This option does not exist in jQuery Validate - there is no validation metod called "name" - and causes a Javascript error when jQuery validate tries to use it:
Cannot read property 'call' of undefined. Exception occurred when checking element name, check the 'name' method.
This means that the "remote" validation never executes because the script crashes before it gets to it.
See https://jsfiddle.net/09djba33/10/ to see the broken functionality - open the Developer Tools and submit the form (with the name field completed), and watch the error message appear in the console.
and https://jsfiddle.net/09djba33/12/ to see the "remote" method working correctly without that spurious option.
P.S. This is why, in the comments, I kept asking you to check what was happening to your ajax request, by looking in the browser tools... :-)
From reading the docs https://jqueryvalidation.org/remote-method/ you can see that while using remote, you need to send data to your server side script because you are using post method. Do it in this way :
remote: {
url: "../includes/check.php",
type: "post"
data: {
username: function () {
return $('#username').val();
}
},

Jquery validation plugin - check if email exists

I'm trying to check on email field blur, if the email already exists in db. My code is now:
<script type="text/javascript">
$(document).ready(function () {
// Validation
$("#soutez").validate({
rules: {
email: {
required: true,
email: true,
remote: "check-email.php",
},
},
messages:{
email:'Email address exists.'
},
onkeyup: false,
onblur: true,
});
});
</script>
And the php code is
$email= $_GET['email'];
echo $email;
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
global $wpdb;
$email_exists = $wpdb->get_row('SELECT COUNT(*) as count from reg_form_new WHERE email = "'.$email.'"');
if ( $email_exists->count == 0 ) { echo 'true'; } else { echo 'false'; }
exit; }
The php code returns true/false correctly, but for some reason it doesn't work with the jQuery script. Anyone can tell me what I'm doing wrong? Thanks
You have to echo exactly the string 'true' and nothing else if you want it to be allowed through. Anything else ('false',null,undefined, or any string) will be interpreted as invalid and if there is a string, that string will be displayed.
So check carefully that your php script is printing out only 'true' or 'false' for now. The script as you've shown it prints the email followed by 'true' or 'false'. This will always be interpreted as false.
Read the documentation of the remote method:
The response is evaluated as JSON and must be true for valid
elements, and can be any false, undefined or null for invalid
elements, using the default message; or a string, eg. "That name is
already taken, try peter123 instead" to display as the error message.
Use Firebug or Chrome Inspector to verify that your response is correct.
I'm not an expert in Jquery, you can to adapt the working function to your need:
$.ajax({
url: "check-email.php",
type:'GET',
/*you my specify dataType: 'json', for example ...*/
data: $("#soutez").serialize(), //email input id
success: function(res) {
switch(res) {
case ('true'):
alert("true");
break;
case ('false'):
alert('false');
break;
// other cases...
}
}
});

jquery validation of email field with php, mysql and validate plugin

I'm having some strange problems using the validation plugin with jquery. This seems to have been asked a few times, but i cannot find the answer to my problem. I've got a form, and I am trying to see if the email has already been entered - if it has, the user should not be able to submit the form. I'm using FirePHP to output various variables. This is where I notice that the return value of my query is always "1" (which is wrong). However, when I manually query my db (using PhpMyAdmin), the correct answer ("0") comes up.
Here is my js:
// validate signup form on keyup and submit
$("#register").validate({
rules: {
......
email: {
required: true,
email: true,
remote: "check_email.php" , async:false
},
},
messages: {
......
email: {required: "Please enter an email address", email: "Please enter a valid email address", remote: "This email is already registered" },
}
}
});
});
And here is my php after the db connection stuff...
$form_email = $_GET['email'];
fb($form_email);
$sql = "SELECT COUNT(*) AS num_rows FROM users WHERE email = " . "'" . $form_email . "'";
fb($sql);
$result = $conn->query($sql);
fb($result->num_rows);
if ($result->num_rows == 0) {
echo 'true';
fb("true");
} else {
echo 'false';
fb("false");
}
The count is always returned as "1", even when I input an email that does not exist.
I've also tried returning
echo json_encode('true');
as I read somewhere that might work, but it did not help. Why is my response always wrong in my php?
The syntax of your remote rule is not correct:
rules: {
......
email: {
required: true,
email: true,
remote: "check_email.php" , async:false
},
}
The way you've written it, the plugin is seeing async as just another rule. Since there is no such "rule" as async, the plugin will choke.
Following the documentation, try this:
rules: {
......
email: {
required: true,
email: true,
remote: "check_email.php"
}
}
or this...
rules: {
......
email: {
required: true,
email: true,
remote: {
url: "check_email.php",
async: false
}
}
}
DEMO: http://jsfiddle.net/KkBSY/

How to make jQuery Validator remotely trigger errorPlacement?

Can anyone please tell me how I can get the jQuery Validator to call the errorPlacement handler when a remote function fails? I have provided a short example:
Cliff Notes: According to their documents, I have to output JSON, but I must have missed something because do I just echo out json_encode, or do I provide a key like echo json_encode(array('result' => 0)) as it says in this block of text.
JS:
var validator = $("form#signup").validate({
onfocousout: true,
rules: {
email: {
required: true,
email: true,
remote: {
type: "POST",
url: 'test.php',
data: {
email: function() {return $("#email").val();}
}
}
},
errorPlacement: function(error, el) {
console.log('ERR' + $(el).attr('id'));
}
}
});
PHP:
<?php
echo false; // This should allow the errorPlacement to call shouldn't it?
I think you need to echo false as a string from your PHP script:
<?php
echo 'false';
I've created a jsfiddle based on your question. The pastebin link just returns the word "false".

Categories