Jquery validation plugin - check if email exists - php

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...
}
}
});

Related

Ajax post does not give value to php file, post becomes get

I have this ajax function for login.
Edit: I just noticed that this server runs php7 while other server where the login does work uses php5. What has changed in php that this script doesn't work anymore?
Edit 2: Looks like the server request method isn't post but changed to get, why?
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
var InName = $('#InName').val();
var InPass = $('#InPass').val();
alert(InName);
$.ajax({
type: "POST",
url: "./ajaxcall/login.php",
dataType: "json",
data: {InName:InName, InPass:InPass},
error: function (request, error) {
console.log(arguments);
alert("Inlog Can't do because: " + error);
},
success : function(data){
if (data.code == "200"){
$("#InErEr").html(data.msg);
//window.location.reload(true);
} else {
$("#InErEr").html(data.msg);
$('.lds-dual-ring').animate({opacity: 0}, 300);
}
}
});
On the alert(InName); I get the correct value of the username. But when I check in my php file $_POST['InName'] it is empty.
Part of php file
include('../config.php');
if(empty($_POST['InName'])) {
$Ierror = 'Username is required.';
}
if($_POST['InPass'] == '') {
$Ierror = 'Password is required.';
}
$username = $_POST['InName'];
$passwordL = $_POST['InPass'];
// count user in between //
if($Inlognumber_of_rows == 0) {
$Ierror = 'Username not found.';
} else {
// password check //
if(password_verify($salty_pass, $hashed_password)) {
} else {
$Ierror = 'Password incorrect.';
}
}
if ($Ierror == '') {
// do login //
} else {
$showerror = '<span style="color:#F00;">'.$Ierror.$username.$passwordL.$_POST['InName'].$_POST['InPass'].'</span>';
echo json_encode(['code'=>404, 'msg'=>$showerror]);
exit;
}
In the return message, $showerror I only get, Username not found, without the posted values. So the login is not working because of empty values? User is also present in the database of course. I also don't get the empty $_POST errors. So to cap up, in javascript I get the correct value for InName but not in php.
You are close but your error catch is not correct ... try this (Jquery):
var InName = 'something';
var InPass = 'morething';
$.post("./ajaxcall/login.php", {
InName: InName,
InPass: InPass
}, function(data, status) {
console.log(data, status);
}).done(function() {
alert("second success");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
on your php file just do print_r($_POST); and you will receive this in your console...:
Array
(
[InName] => something
[InPass] => morething
)
success
Basically you were trying to print the error where you should have consoled log the request.responeText...
A good trick to know if posts arrived to the php even if the console.log won't show is doing this in the php file:
<?php
print_r($_POST) ;
$newfile = fopen('newfile.txt','a');
fwrite($newfile,json_encode($_POST));
fclose($newfile);
This will print and also store on a local file the post data....
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅

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".

php jquery remote validate problem

<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)

jQuery.ajax / CodeIgniter (PHP) : Returning TRUE/FALSE in PHP, how can I get jQuery to see this?

I've built a function for checking a username. I'm using it as a callback for form validation in CodeIgniter, and it works nicely. However, I'd like to also use it with AJAX to check on the fly if the user has JS enabled. So my controller has this:
function check_username($s = FALSE)
{
if ($s):
$this->db_common->like('username', $s);
$query = $this->db_common->get('users');
if ($query->num_rows() > 0):
$this->form_validation->set_message('check_username', 'Username taken. Choose another!');
return FALSE;
else:
return TRUE;
endif;
else:
echo 'Username required';
endif;
}
And my HTML/JS is this:
$(document).ready(function()
{
var delayed;
$("#username").keyup(function()
{
clearTimeout(delayed);
var value = this.value;
if (value)
{
delayed = setTimeout(function() {
$.ajax
({
type: "POST",
url: "<?php echo base_url(); ?>auth/check_username/",
data: $("#username").val(),
success: function(html)
{
$("#username_check").html(html);
}
});
}, 100);
}
});
});
Basically, I'm returning FALSE if the username exists and TRUE if it does exist. How do I get my jQuery AJAX to see that? Basically, I want jQuery to check if it's false, then say 'username exists' and if it's true, then 'username is okay'.
Do something like the following:
echo 'ok';
return TRUE;
The reason for this is that jQuery can't see the boolean values returned by PHP as they're not send to the browser's output.
Basically, I'm returning FALSE if the username exists and TRUE if it does exist. How do I get my jQuery AJAX to see that?
You can't directly. I would output 0 or 1 instead.
I would return true or false as JSON boolean from your PHP script and use javascript's eval() function to evaluate that to a javascript var.
There is a way to do it with PHP and jQuery. Here is an example...
simply have your php script echo back true or false.
PHP-> echo true; or echo false;
$.post("your_url/your_class/your_method", { } ,
function(data) {
if(data) alert('true');
else alert('false');
}, "json")
.error(function() { //alert("an AJAX error occurred!");
});

php validation using jquery and ajax

i have a jquery ajax form.
i have validation at server side for repeated username and email ID.
which works fine without jquery/ajax.
in my php code i have used die() to return if any error occurs. my main problem is at ajax
here is the code
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function () {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
The success function works properly. if my data is valid then it is added in the db, if my data is repeated then it is not added in the db. Now what i want to know is how do i return the error from my php file and use it at success event. Thanks in advance..
edit : this is how my php script looks
$query = "SELECT username from userdetails WHERE username = '$username'";
$q = mysql_query($query) or die("error" . mysql_error());
$numrows = mysql_num_rows($q);
if($numrows > 0)
{
die("username already exixt");
//should i put something like this
//$error = "username already exists";
//return $error; --->> i am not sure about this..
}
thanks in advance
Php side:
if($numrows > 0)
{
echo "username already exist";
}
Javascript side:
success: function(msg)
{
if(msg == 'username already exist') alert(msg);
}
But this is so crude, If you plan to develop this further try to read some articles on JSON, so you can use json to communicate to server side. And also you should try to use some default error controlling, like return an array with php:
echo json_encode(array('error' => true, 'notice' => 'username exists'));
Then on the javascript side (jquery), use json ajax request and always check if error variable is true or not, if it is maybe you can use a default function for error controlling.
Hope this helped.
In the function definition which you have done like:
success: function(){
introduce a parameter like: success: function(retVal){
Now in the function you can check for the value of retVal.
Say, you return from your PHP script, "successful" for success case and "this email exists" for failure.
Now you can directly compare this here and do whatever you want to, like:
if(retVal == 'this email exists')
{
window.alert('please re-enter the email, this record exists!');
}
and so on...
Hope this helps.
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function (msg) {
alert(msg);
}
});
return false;
});
});
Here from server side send the message and show it, how i have shown it :)

Categories