jQuery Validate remote method usage to check if username already exists
I've managed to get this to work by changing the PHP technique I was using, here's my PHP:
<?php
require_once "./source/includes/data.php";
header('Content-type: application/json');
$request = $_REQUEST['username'];
$query = mysql_query("SELECT * FROM mmh_user_info WHERE username ='$username'");
$result = mysql_num_rows($query);
if ($result == 0){
$valid = 'true';}
else{
$valid = 'false';
}
echo $valid;
?>
Thanks everyone here for your help :)
jQuery Validate Remote - Check if email already exists
You have to change the row count if / else condition in query
Script
<script>
$(document).ready(function () {
$('#signup').validate({
errorLabelContainer: "#cs-error-note",
wrapper: "li",
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-username.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please enter your email address.",
email: "Please enter a valid email address.",
remote: "Email already in use!"
}
},
submitHandler: function(form) {
form.submit();
}
});
});
</script>
HTML
<form class="form-inline" role="form" id="signup">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" name="email" id="email">
</div>
</form>
PHP
Warning Do not use this PHP code reason rowCount()
may not work so skip it and jump to code at bottom of answer.
<?php
require('../../private_html/db_connection/connection.php');
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
if(isset($_POST['email'])) {
$email = $_POST['email'];
$query = $conn->prepare("SELECT email FROM user_accounts WHERE email = '$email'");
$query->execute();
if( $query->rowCount() > 0 ){
echo 'false';
} else {
echo 'true';
}
}
?>
Edit: As @Jay Blanchard very consistent and dead sure that above code will not work
rowCount() doesn't work for SELECT statements. stackoverflow.com/a/31569733/1011527
Nope, this will not work because rowCount() doesn't work for SELECT statements. You're not getting a row count at all.
Try echoing $query->rowCount() and you'll see the issue
and makes me wonder How the above code is working on my live server when It shouldn't so I done some digging and found this;
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
and this
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
Source of Above statements php.net manuals
In both above statements, some databases and For most databases rowCount()
does work but on other-hand
- should not be relied on for portable applications
- use PDOStatement::fetchColumn() to retrieve the number of rows that will
be returned. Your application can then perform the correct action.
As OP only wants the count of rows and not all the data of all the rows so can be also done like this. Credit goes to @Jay Blanchard
Use This Code Example
made some changes in PHP, use isset
function.
<?php
require('../../private_html/db_connection/connection.php');
$conn = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
if(isset($_POST['email'])) {
$email = $_POST['email'];
$query = $conn->prepare("SELECT email FROM user_accounts WHERE email = '$email'");
$query->execute();
$rows = $query->fetchAll();
$total_rows = count($rows);
if( $total_rows > 0 ){
echo 'false';
} else {
echo 'true';
}
}
?>
See in Action
Jquery Validation check username with remote
It doesn't look like you are sending the data. Try this. Note the post request. Also I believe the dataFilter method should return 'true'
.
Update I just also realized the logic in your php is sending back true if the user exists, therefore the logic in the javascript should be like so:
remote: {
url: "http://"+location.host+"/validation/checkusername",
type: "post",
data: {
username: function () {
return $("input[name='username']").val();
}
},
dataFilter: function (data) {
var json = JSON.parse(data);
if (json.msg == "true") {
return "\"" + "That username is taken" + "\"";
} else {
return 'true';
}
}
}
php - jQuery.validator.addMethod check username
You should be using the remote
method, which has already been tested and proven for this exact purpose. There is no reason to reinvent something that's already been done.
rules: {
username: {
required: true,
minlength: 3,
maxlength: 25,
letters: true,
remote: { // value of 'username' field is sent by default
type: 'POST',
url: 'checkname.php'
}
}
....
Your checkname.php
include 'connect.php';
if (isSet($_POST['username']))
{
$username = mysql_real_escape_string($_POST['username']);
$check_for_username = mysql_query("SELECT * FROM user WHERE username='$username'");
if (mysql_num_rows($check_for_username) > 0)
{
echo json_encode("Username is Already Taken");
// you could even try something like this:
// echo json_encode($username . " is Already Taken");
}
else
{
echo "true";
}
}
NOTE: mysql_
has been deprecated in PHP and should be replaced with mysqli
or pdo_mysql
. See: php.net/manual/en/function.mysql-query.php
Also see: jQuery Validate remote method usage to check if username already exists
jQuery Validator Plugin - check for existing Username/Email in mysql database
$.validator.addMethod("checkExists", function(value, element)
{
var inputElem = $('#register-form :input[name="email"]'),
data = { "emails" : inputElem.val() },
eReport = ''; //error report
$.ajax(
{
type: "POST",
url: validateEmail.php,
dataType: "json",
data: data,
success: function(returnData)
{
if (returnData!== 'true')
{
return '<p>This email address is already registered.</p>';
}
else
{
return true;
}
},
error: function(xhr, textStatus, errorThrown)
{
alert('ajax loading error... ... '+url + query);
return false;
}
});
}, '');
OR
You can use the remote method instead which allows you to do remote checks: http://docs.jquery.com/Plugins/Validation/Methods/remote
Eg.
$("#yourFormId").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "checkUnameEmail.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please Enter Email!",
email: "This is not a valid email!",
remote: "Email already in use!"
}
}
});
checkUnameEmail.php //Eg.
<?php
$registeredEmail = array('jenson1@jenson.in', 'jenson2@jenson.in', 'jenson3@jenson.in', 'jenson4@jenson.in', 'jenson5@jenson.in');
$requestedEmail = $_REQUEST['email'];
if( in_array($requestedEmail, $registeredEmail) ){
echo 'false';
}
else{
echo 'true';
}
?>
Related Topics
Automatically Deleting Related Rows in Laravel (Eloquent Orm)
Commands Out of Sync; You Can't Run This Command Now
How to Use Multiple Databases in Laravel
When Should I Use 'Self' Over '$This'
How to Compare Two Datetime Objects in PHP 5.2.8
How to Get an Array of Specific "Key" in Multidimensional Array Without Looping
Suppress Error With @ Operator in PHP
How to Set Up File Permissions For Laravel
Using a String Path to Set Nested Array Data
PHP Ini File_Get_Contents External Url
How to Get Innerhtml of Domnode
How to Validate an Email Address in PHP
How to Access Object Properties With Names Like Integers or Invalid Property Names