I am new to php and jQuery, I have googled a day but couldn't solve the problem. I want to check if the username is taken or not, but what I got is "Username is Already Taken" no matter what I enter.
so here is my code:
$(document).ready(function(){
$('#registration-form').validate({
rules: {
username: {
required: true,
minlength: 3,
maxlength: 25,
letters: true,
checkUsername: true,
},
password: {
required: true,
minlength: 6,
maxlength: 12
},
confirmpassword: {
required: true,
minlength: 6,
maxlength: 12,
equalTo: "#password"
},
email: {
required: true,
email: true
},
country:{
required: true,
}
},
highlight: function(element) {
$(element).closest('.form-group').addClass('error');
$(element).removeClass("valid");
},
success: function(element) {
element
.addClass('valid')
.closest('.form-group').removeClass('error');
}
});
$(".close, #close").click(function() {
$("label.error").hide();
$(".error").removeClass("error");
$("input.valid").removeClass("valid");
});
$.validator.addMethod("letters", function(value, element) {
return this.optional(element) || value == value.match(/^[a-zA-Z_]+$/);
},"Letters and underscore only.");
$.validator.addMethod("checkUsername", function(value, element){
var response='';
$.ajax({
type: "POST",
url: 'checkname.php',
data:"username="+value,
async:false,
success:function(data){
response = data;
}
});
if(response == 0)
{
return true;
}
else
{
return false;
}
}, "Username is Already Taken");
});
Here is my checkname.php
<?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 "false";
} else {
echo "true";
}
}
?>
Please help me, I am so frustrated .....
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
Related
I have script like this:
const add_modal = $('#add_modal');
const add_form = $('#add_form');
const add_button = $('#add_button');
const save_button = $('#save_button');
let add_validator = add_form.validate({
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-invalid-label',
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
// Different components require proper error label placement
errorPlacement: function(error, element) {
// Unstyled checkboxes, radios
if (element.parents().hasClass('form-check')) {
error.appendTo( element.parents('.form-check').parent() );
}
// Input with icons and Select2
else if (element.parents().hasClass('form-group-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo( element.parent() );
}
// Input group, styled file input
else if (element.parent().is('.uniform-uploader, .uniform-select') || element.parents().hasClass('input-group')) {
error.appendTo( element.parent().parent() );
}
// Other elements
else {
error.insertAfter(element);
}
},
rules: {
name: {
required: true,
minlength: 2,
maxlength: 20
},
email: {
required: true,
email: true,
remote: "/admin/users/check-email",
},
role: {
required: true,
},
password: {
required: true,
minlength: 12,
},
password_verification: {
required: true,
minlength: 12,
equalTo: '#password'
},
},
messages:{
email:{
remote: "Email is already taken."
}
}
});
add_button.click(function (e) {
e.preventDefault();
add_modal.modal("show");
add_validator.resetForm();
$(':input').val("");
$("#csrf").val($csrf);
});
save_button.click(function (e) {
e.preventDefault();
let form = $(this).closest('form');
let $action = form.attr('action');
let $method = form.attr('method');
let $data = form.serialize();
if (add_form.valid()) {
$.ajax({
url: $action,
type: $method,
data:$data,
success: function (result) {
if (result.type === 'success') {
add_modal.modal("hide");
add_validator.resetForm();
swalInit({
title: 'Success!',
text: result.text,
type: 'success',
timer: 3000,
}).then((reload) => {
datatables.ajax.reload();
});
} else {
swalInit({
title: 'Oops...',
text: result.text,
type: 'error',
timer: 3000,
});
}
},
})
}
});
it seems like the jqueryvalidation plugin is checking mail availability on modals open. since when I see at web inspector it sends a post request to /admin/users/check-email. how can i prevent this behaviour and make it only check when i press save_button? save_button is a button inside the modal.
Try this:
let update_validator = update_form.validate({
ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
errorClass: 'validation-invalid-label',
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
unhighlight: function(element, errorClass) {
$(element).removeClass(errorClass);
},
// Different components require proper error label placement
errorPlacement: function(error, element) {
// Unstyled checkboxes, radios
if (element.parents().hasClass('form-check')) {
error.appendTo( element.parents('.form-check').parent() );
}
// Input with icons and Select2
else if (element.parents().hasClass('form-group-feedback') || element.hasClass('select2-hidden-accessible')) {
error.appendTo( element.parent() );
}
// Input group, styled file input
else if (element.parent().is('.uniform-uploader, .uniform-select') || element.parents().hasClass('input-group')) {
error.appendTo( element.parent().parent() );
}
// Other elements
else {
error.insertAfter(element);
}
},
rules: {
name: {
required: true,
minlength: 2,
maxlength: 20
},
email: {
required: true,
email: true,
remote: {
url: "/admin/users/email-available",
type: "post",
data: {
user_id: function () {
return $("#id").val();
}
}
}
},
role: {
required: true,
},
password: {
minlength: 12
},
password_verification: {
required: isPasswordPresent,
minlength: 12,
equalTo: "#update_password"
},
},
messages:{
email:{
remote: "Email is already taken."
}
},
submitHandler: function(form, event) {
event.preventDefault();
let $action = $(form).attr('action');
let $method = $(form).attr('method');
let $data = $(form).serialize();
$.ajax({
url: $action,
type: $method,
data: $data,
success: function (result) {
if (result.type === 'success') {
update_modal.modal("hide");
update_validator.resetForm();
swalInit({
title: 'Success!',
text: result.text,
type: 'success',
timer: 3000,
showCloseButton: true
}).then((reload) => {
datatables.ajax.reload();
});
} else {
swalInit({
title: 'Oops...',
text: result.text,
type: 'error',
timer: 3000,
});
}
},
})
}
});
I want the email field to be validated in correct format
function editAccount() {
$("#editacc").validate({
rules: {
email: {
remote: {
url: "../accounts/check-email.php?type=email",
type: "get",
data: {
email: function() {
return $( "#email" ).val();
},
id:function(){
return $( "#userid" ).val();
}
}
}
},
imeino: {
remote: {
url: "../accounts/check-email.php?type=imeino",
number: true,
type: "get",
data: {
imeino: function() {
return $( "#imeino" ).val();
},
id:function(){
return $( "#userid" ).val();
}
}
}
},
username: {
remote: {
url: "../accounts/check-email.php?type=username",
type: "get",
data: {
imeino: function() {
return $( "#username" ).val();
},
id:function(){
return $( "#userid" ).val();
}
}
}
},
mobileno: {
minlength: 10,
number: true
},
accounttype:"accountcheck"
},
messages:{
email: {
email: "Invalid Email Address",
remote: "Email ID Already registered"
},
imeino: {
remote: "IMEI No Exists",
},
username: {
remote: "Username Exists"
},
accounttype:"Imei no required for Agent",
firstname:"Firstname Required",
lastname:"Lastname Required",
mobileno:"Mobile Number Required with numbers",
email:"Email Id Required with valid format!!",
reportingstaff:"Reporting Staff Required"
},
Email is not validating in correct format.
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
}
}
});
/*************** check-email.php **************/
< ?php
/* check if email is already registered */
//connect to db using mysqli
if (!empty($_POST['email']))
{
$email = $mysqli->real_escape_string($_POST['email']);
$query = "SELECT ID FROM users WHERE user_email = '{$email}' LIMIT 1;";
$results = $mysqli->query($query);
if($results->num_rows == 0)
{
echo "true"; //good to register
}
else
{
echo "false"; //already registered
}
}
else
{
echo "false"; //invalid post var
}
?>
$("#da-ex-validate2").validate({
rules: {
details: {
required: true,
rangelength: [1, 500]
},
editor1: {
required: true,
minlength: 1
},
title: {
required: true,
rangelength: [1, 100]
},
SlideDeckPhoto: {
required: "#iButton:checked",
accept: ['.jpeg', '.png', '.jpg', '.gif']
},
min1: {
required: true,
digits: true,
min: 5
},
max1: {
required: true,
digits: true,
max: 5
},
submitHandler: function(form) {
$(form).ajaxSubmit();
},
range1: {
required: true,
digits: true,
range: [5, 10]
}
},
invalidHandler: function (form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("#da-ex-val2-error").html(message).show();
} else {
$("#da-ex-val2-error").hide(); // it's not work !!! and the page is reload !!
}
}
});
I would also would like to save my form values to MySql without reload the page .
Please help ! I read so many post and tried so many thing !
If you put a code please tell where to put it ..
BTW my form has few input fields and also an file input field .
PLEASE HELP !
return false from the submit handler
submitHandler: function(form) {
$(form).ajaxSubmit();
return false;
}
This is my solution, put it after invalidHandler :
submitHandler: function(form) {
var dataString = $('#YourFormID').serialize();
$.ajax({
type: 'POST',
url: 'yourpage.php',
data: dataString,
success: function() {
$('#YourErrorDivID').hide();
$('#YourSuccessDivID').html("Your Message").show();
}
});
}
I am validating my form using jquery as below:
jQuery(document).ready(function(){
jQuery('#adminform').validate({
rules: {
name: {
minlength: 5,
maxlength: 30,
required: true
},
username: {
required: true,
minlength: 5,
maxlength: 30
}
},
highlight: function(label) {
jQuery(label).closest('.control-group').addClass('error');
},
success: function(label) {
label
.text('OK!').addClass('valid')
.closest('.control-group').addClass('success');
},
messages:{
name: {
required: "Enter your name"
},
username: {
required: "Enter a username"
}
}
});
});
now how should I prevent the form from submission if the rules are not meet?
When I click the submit button nothing should happen.
To stop a form being submitted you use:
return false;
When you know the input is invalid.
Prevent form submission using jQuery?
$('#myFormId').submit(function(event) {
event.preventDefault();
});
OR:
$('#myFormId').submit(function()
{
return false;
});
Prevent the submit event and remain on the screen
e.preventDefault();
what about this?
Your code is perfect just a submit trigger needed : http://jsfiddle.net/uUdWN/
jQuery(document).ready(function() {
jQuery('#adminform').validate({
rules: {
name: {
minlength: 5,
maxlength: 30,
required: true
},
username: {
required: true,
minlength: 5,
maxlength: 30
}
},
highlight: function(label) {
jQuery(label).closest('.control-group').addClass('error');
},
success: function(label) {
label.text('OK!').addClass('valid').closest('.control-group').addClass('success');
},
messages: {
name: {
required: "Enter your name"
},
username: {
required: "Enter a username"
}
}
});
$("#adminform").submit(); // <-------------just triggered submit
});
I am very new to jQuery and javascript programming. I have a program below that checks whether username is taken or not. For now, the PHP script always returns
if(isset($_POST["username"]) )//&& isset($_POST["checking"]))
{
$xml="<register><message>Available</message></register>";
echo $xml;
}
Login function works, but username checking doesn't. Any ideas?
Here is all of my code:
$(document).ready(function() {
jQuery.validator.addMethod("checkAvailability",function(value,element){
$.post( "login.php" , {username:"test", checking:"yes"}, function(xml){
if($("message", xml).text() == "Available") return true;
else return false;
});
},"Sorry, this user name is not available");
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 4,
checkAvailability: true
},
password:{
required: true,
minlength: 5
}
},
messages: {
username:{
required: "You need to enter a username." ,
minlength: jQuery.format("Your username should be at least {0} characters long.")
}
},
highlight: function(element, errorClass) {
$(element).fadeOut("fast",function() {
$(element).fadeIn("slow");
})
},
success: function(x){
x.text("OK!")
},
submitHandler: function(form){send()}
});
function send(){
$("#message").hide("fast");
$.post( "login.php" , {username:$("#username").val(), password:$("#password").val()}, function(xml){
$("#message").html( $("message", xml).text() );
if($("message", xml).text() == "You are successfully logged in.")
{
$("#message").css({ "color": "green" });
$("#message").fadeIn("slow", function(){location.reload(true);});
}
else
{
$("#message").css({ "color": "red" });
$("#message").fadeIn("slow");
}
});
}
$("#newUser").click(function(){
return false;
});
});
It's OK, and working now. Here is the code:
$(document).ready(function() {
jQuery.validator.addMethod("checkAvailability",function(value,element){
var x= $.ajax({
url: "login.php",
type: 'POST',
async: false,
data: "username=" + value + "&checking=true",
}).responseText;
if($("message", x).text()=="true") return true;
else return false;
},"Sorry, this user name is not available");
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 4,
checkAvailability: true
},
password:{
required: true,
minlength: 5
}
},
messages: {
username:{
required: "You need to enter a username." ,
minlength: jQuery.format("Your username should be at least {0} characters long.")
}
},
highlight: function(element, errorClass) {
$(element).fadeOut("fast",function() {
$(element).fadeIn("slow");
})
},
success: function(x){
x.text("OK!")
},
submitHandler: function(form){send()}
});
function send(){
$("#message").hide("fast");
$.post( "login.php" , {username:$("#username").val(), password:$("#password").val()}, function(xml){
$("#message").html( $("message", xml).text() );
if($("message", xml).text() == "You are successfully logged in.")
{
$("#message").css({ "color": "green" });
$("#message").fadeIn("slow", function(){location.reload(true);});
}
else
{
$("#message").css({ "color": "red" });
$("#message").fadeIn("slow");
}
});
}
$("#newUser").click(function(){
return false;
});
});
You need to use the expanded form of $.post() which is $.ajax() so you can set the async option to false, like this:
jQuery.validator.addMethod("checkAvailability",function(value,element){
$.ajax({
url: "login.php",
type: 'POST',
async: false,
data: {username:"test", checking:"yes"},
success: function(xml) {
return $("message", xml).text() == "Available";
}
});
},"Sorry, this user name is not available");
Currently your success function that analyzes the response happens after the validation finishes, because it's an asynchronous operation. So currently, it's not returning anything at the time the return value is used, and undefined ~= false, which is why it always appears false. By setting async to false, you're letting the code execute in order without the callback, so the return in the example above is actually used.
Another alternative, if you can adjust your page's return structure is to use the validation plugin's built-in remote option, which is for just this sort of thing :)
OK, this might not be all that relevant but I had a similar issue. I didn't do anything with the return value, I just returned it. And it always was true. So, after some poking around I figured that the value from the server appeared as a String to the validator. So long as it was not an empty string it would return true. So the solution was to use eval();
An example:
jQuery.validator.addMethod("checkAvailability",function(value,element){
return eval($.ajax({
url: "/check",
async: false,
data: {
field: $('#element').attr('name'),
val: value
}
}).responseText);
}, "error");