I'm using the jQuery validation plugin to check if the user excists in my SQL database. I want to check the credentials in checkCredentials.php. My script does check if an email or password is filled in but it does not check if the credentials do exist in my database. Anybody who can tell me what I'm doing wrong? Thanks in advance.
This is my form:
<form action="php/login.php" method="post" id="loginForm" class="form-horizontal">
<div class="form-group">
<input type="email" class="form-control form-control-lg" id="email" name="email" placeholder="Email" />
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" id="password" name="password" placeholder="Wachtwoord" />
</div>
<button class="btn btn-block" type="submit" name="login" value="Login">Login</button>
</form>
And this is my script:
$( "#loginForm" ).validate( {
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
remote: {
url: "php/checkCredentials.php",
type: "post",
data: {
email: function () {
return $("#email").val();
}
}
}
},
},
messages: {
email: {
required: "Vul alsjeblieft een e-mail adres in"
},
password: {
required: "Vul alsjeblieft een wachtwoord in",
remote: "E-mail of wachtwoord onjuist"
},
},
And here is my PHP file checkCredentials.php
<?php
require 'database-connection.php';
$email = mysqli_real_escape_string($_REQUEST['email']);
$password = mysqli_real_escape_string($_REQUEST['password']);
$query = "SELECT user_email, user_password FROM table_users WHERE user_email = '$email' AND user_password = '$password'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) == 0)
{
echo 'true';
}
else
{
echo 'false';
}
?>
I changed my code to this and it's working now:
Form:
<form action="php/login.php" method="post" id="loginForm" class="form-horizontal">
<div class="form-group">
<input type="email" class="form-control form-control-lg" id="email" name="email" placeholder="Email" />
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" id="password" name="password" placeholder="Wachtwoord" />
</div>
<button class="btn btn-block" type="submit" name="login" value="Login">Login</button>
</form>
Script:
$( "#loginForm" ).validate( {
rules: {
email: {
required: true,
email: true
},
password: {
required: true,
remote: {
url: "php/checkCredentials.php",
type: "post",
data: {
email: function () {
return $("#email").val();
}
}
}
},
},
messages: {
email: {
required: "Vul alsjeblieft een e-mail adres in"
},
password: {
required: "Vul alsjeblieft een wachtwoord in",
remote: "E-mail of wachtwoord onjuist"
},
},
errorElement: "em",
errorPlacement: function ( error, element ) {
error.addClass( "help-block" );
element.parents( ".col-sm-5" ).addClass( "has-feedback" );
if ( element.prop( "type" ) === "checkbox" ) {
error.insertAfter( element.parent( "label" ) );
} else {
error.insertAfter( element );
}
if ( !element.next( "span" )[ 0 ] ) {
$( "<span class='glyphicon glyphicon-remove form-control-feedback'></span>" ).insertAfter( element );
}
},
success: function ( label, element ) {
if ( !$( element ).next( "span" )[ 0 ] ) {
$( "<span class='glyphicon glyphicon-ok form-control-feedback'></span>" ).insertAfter( $( element ) );
}
},
highlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-5" ).addClass( "has-error" ).removeClass( "has-success" );
$( element ).next( "span" ).addClass( "glyphicon-remove" ).removeClass( "glyphicon-ok" );
},
unhighlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-error" );
$( element ).next( "span" ).addClass( "glyphicon-ok" ).removeClass( "glyphicon-remove" );
}
} );
</script>
checkCredentials.php:
<?php
require 'database-connection.php';
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$query = "SELECT user_email, user_password FROM table_users WHERE user_email = '$email' AND user_password = '$password'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) > 0)
{
echo 'true';
}
else
{
echo 'false';
}
?>
Related
I have the problem of not submitting the user registration data (such as email, username, password) in a register table tbl_register on submit button click.
I am using PHP with AJAX so that my page not refreshes on submit click and data is send to mysql table using action php page registersubmit.php.
I have files as
1) register.php - which has register and login form
2) registersubmit.php - which receives the submit click
3) connection.php - to make database connection.
code for above files are as follows:
1) register.php
<div class="form-wrap">
<div class="tabs">
<h3 class="signup-tab"><a class="active" href="#signup-tab-content">Sign Up</a></h3>
<h3 class="login-tab">Login</h3>
</div><!--.tabs-->
<div class="tabs-content">
<div id="signup-tab-content" class="active">
<form class="signup-form" action="" method="post">
<input type="email" class="input" name="user_email" autocomplete="off" placeholder="Email">
<input type="text" class="input" name="user_name" autocomplete="off" placeholder="Username">
<input type="password" class="input" name="user_pass" autocomplete="off" placeholder="Password">
<input type="submit" class="button" name="registersubmit" id="registersubmit" value="Sign Up">
</form><!--.login-form-->
<div class="message_box" style="margin:10px 0px;"></div>
<div class="help-text">
<p>By signing up, you agree to our</p>
<p>Terms of service</p>
</div><!--.help-text-->
</div><!--.signup-tab-content-->
<div id="login-tab-content">
<form class="login-form" action="" method="post">
<input type="text" class="input" name="user_login" autocomplete="off" placeholder="Email or Username">
<input type="password" class="input" name="user_pass" autocomplete="off" placeholder="Password">
<input type="checkbox" class="checkbox" id="remember_me">
<label for="remember_me">Remember me</label>
<input type="submit" class="button" id="loginsubmit" name="loginsubmit" value="Login">
</form><!--.login-form-->
<div class="message_box" style="margin:10px 0px;"></div>
<div class="help-text">
<p>Forget your password?</p>
</div><!--.help-text-->
</div><!--.login-tab-content-->
</div><!--.tabs-content-->
</div><!--.form-wrap-->
<script>
jQuery(document).ready(function($) {
tab = $('.tabs h3 a');
tab.on('click', function(event) {
event.preventDefault();
tab.removeClass('active');
$(this).addClass('active');
tab_content = $(this).attr('href');
$('div[id$="tab-content"]').removeClass('active');
$(tab_content).addClass('active');
});
});
</script>
<script>
$(document).ready(function() {
var delay = 2000;
$('#registersubmit').click(function(e){
e.preventDefault();
var user_name = $('[name="user_name"]').val();
if(user_name == ''){
$('.message_box').html(
'<span style="color:red;">Enter Your Name!</span>'
);
$('[name="user_name"]').focus();
return false;
}
var user_email = $('[name="user_email"]').val();
if(user_email == ''){
$('.message_box').html(
'<span style="color:red;">Enter Email Address!</span>'
);
$('[name="user_email"]').focus();
return false;
}
if( $('[name="user_email"]').val()!='' ){
if( !isValidEmailAddress( $('[name="user_email"]').val() ) ){
$('.message_box').html(
'<span style="color:red;">Provided email address is incorrect!</span>'
);
$('[name="user_email"]').focus();
return false;
}
}
var user_pass = $('[name="user_pass"]').val();
if(user_pass == ''){
$('.message_box').html(
'<span style="color:red;">Password cannot be empty!</span>'
);
$('[name="user_pass"]').focus();
return false;
}
$.ajax
({
type: "POST",
url: "registersubmit.php",
data: "name="+user_name+"&email="+user_email+"&password="+user_pass,
beforeSend: function() {
$('.message_box').html(
'<img src="Loader.gif" width="25" height="25"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, delay);
}
});
});
$('#loginsubmit').click(function(e){
e.preventDefault();
var user_name = $('[name="user_name"]').val();
if(user_name == ''){
$('.message_box').html(
'<span style="color:red;">Enter Your Name!</span>'
);
$('[name="user_name"]').focus();
return false;
}
var user_email = $('[name="user_email"]').val();
if(user_email == ''){
$('.message_box').html(
'<span style="color:red;">Enter Email Address!</span>'
);
$('[name="user_email"]').focus();
return false;
}
if( $('[name="user_email"]').val()!='' ){
if( !isValidEmailAddress( $('[name="user_email"]').val() ) ){
$('.message_box').html(
'<span style="color:red;">Provided email address is incorrect!</span>'
);
$('[name="user_email"]').focus();
return false;
}
}
var user_pass = $('[name="user_pass"]').val();
if(user_pass == ''){
$('.message_box').html(
'<span style="color:red;">Password cannot be empty!</span>'
);
$('[name="user_pass"]').focus();
return false;
}
$.ajax({
type: "POST",
url: "loginsubmit.php",
data: "name="+user_name+"&email="+user_email+"&password="+user_pass,
beforeSend: function() {
$('.message_box').html(
'<img src="Loader.gif" width="25" height="25"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, delay);
}
});
});
</script>
<script>
//Email Validation Function
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
};
</script>
2) registersubmit.php
<?php
if ( ($_POST['name']!="") && ($_POST['email']!="")){
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
include('connection.php');
/* check connection */
if ($conn->connect_errno) {
printf("Connect failed: %s\n", $conn->connect_error);
exit();
}
//insert query for registration
$insertSql = "INSERT INTO `tbl_register`(`Email`, `UserName`, `Password`) VALUES ('$email','$name', '$password')";
if ($conn->query($insertSql) === TRUE) {
}else{
printf("Error: %s\n", $conn->error);
}
}
?>
3) connection.php
<?php
// set the timezone first
if(function_exists('date_default_timezone_set')) {
date_default_timezone_set("Asia/Kolkata");
}
//create a mysql connection
$conn = new mysqli('localhost','root','');
//check connection
if($conn->connect_error){
die("Connection Failed".$conn->connect_error);
}
//connect database
mysqli_select_db($conn, "my_db");
?>
Please help, after that i will solve the same problem for login also. But for now no entry received in my tbl_register table.
Try This >
<div class="form-wrap">
<div class="tabs">
<h3 class="signup-tab"><a class="active" href="#signup-tab-content">Sign Up</a></h3>
<h3 class="login-tab">Login</h3>
</div><!--.tabs-->
<div class="tabs-content">
<div id="signup-tab-content" class="active">
<form class="signup-form" id="signup-form" name="signup-form" action="" method="post">
<input type="email" class="input" name="user_email" autocomplete="off" placeholder="Email">
<input type="text" class="input" name="user_name" autocomplete="off" placeholder="Username">
<input type="password" class="input" name="user_pass" autocomplete="off" placeholder="Password">
Sign Up
</form>
<!--.login-form-->
<div class="message_box" style="margin:10px 0px;"></div>
<div class="help-text">
<p>By signing up, you agree to our</p>
<p>Terms of service</p>
</div><!--.help-text-->
</div><!--.signup-tab-content-->
<div id="login-tab-content">
<form class="login-form" id="login-form" name="login-form" action="" method="post">
<input type="text" class="input" name="user_login" autocomplete="off" placeholder="Email or Username">
<input type="password" class="input" name="user_pass" autocomplete="off" placeholder="Password">
<input type="checkbox" class="checkbox" id="remember_me">
<label for="remember_me">Remember me</label>
Login
</form><!--.login-form-->
<div class="message_box" style="margin:10px 0px;"></div>
<div class="help-text">
<p>Forget your password?</p>
</div><!--.help-text-->
</div><!--.login-tab-content-->
</div><!--.tabs-content-->
</div><!--.form-wrap-->
<script>
jQuery(document).ready(function ($) {
tab = $('.tabs h3 a');
tab.on('click', function (event) {
event.preventDefault();
tab.removeClass('active');
$(this).addClass('active');
tab_content = $(this).attr('href');
$('div[id$="tab-content"]').removeClass('active');
$(tab_content).addClass('active');
});
});
</script>
<script>
$(document).ready(function() {
var delay = 2000;
$('#registersubmit').click(function(e){
e.preventDefault();
var user_name = $('[name="user_name"]').val();
if (user_name == ''){
$('.message_box').html(
'<span style="color:red;">Enter Your Name!</span>'
);
$('[name="user_name"]').focus();
return false;
}
var user_email = $('[name="user_email"]').val();
if (user_email == ''){
$('.message_box').html(
'<span style="color:red;">Enter Email Address!</span>'
);
$('[name="user_email"]').focus();
return false;
}
if ($('[name="user_email"]').val() != ''){
if (!isValidEmailAddress($('[name="user_email"]').val())){
$('.message_box').html(
'<span style="color:red;">Provided email address is incorrect!</span>'
);
$('[name="user_email"]').focus();
return false;
}
}
var user_pass = $('[name="user_pass"]').val();
if (user_pass == ''){
$('.message_box').html(
'<span style="color:red;">Password cannot be empty!</span>'
);
$('[name="user_pass"]').focus();
return false;
}
var registerFormData = jQuery("#signup-form").serialize();
$.ajax({
type: "POST",
url: "registersubmit.php",
data: registerFormData,
beforeSend: function() {
$('.message_box').html(
'<img src="Loader.gif" width="25" height="25"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, delay);
}
});
});
$('#loginsubmit').click(function(e){
e.preventDefault();
var user_name = $('[name="user_name"]').val();
if (user_name == ''){
$('.message_box').html(
'<span style="color:red;">Enter Your Name!</span>'
);
$('[name="user_name"]').focus();
return false;
}
var user_email = $('[name="user_email"]').val();
if (user_email == ''){
$('.message_box').html(
'<span style="color:red;">Enter Email Address!</span>'
);
$('[name="user_email"]').focus();
return false;
}
if ($('[name="user_email"]').val() != ''){
if (!isValidEmailAddress($('[name="user_email"]').val())){
$('.message_box').html(
'<span style="color:red;">Provided email address is incorrect!</span>'
);
$('[name="user_email"]').focus();
return false;
}
}
var user_pass = $('[name="user_pass"]').val();
if (user_pass == ''){
$('.message_box').html(
'<span style="color:red;">Password cannot be empty!</span>'
);
$('[name="user_pass"]').focus();
return false;
}
var loginFormData = jQuery("#login-form").serialize();
$.ajax({
type: "POST",
url: "loginsubmit.php",
data: loginFormData,
beforeSend: function() {
$('.message_box').html(
'<img src="Loader.gif" width="25" height="25"/>'
);
},
success: function(data)
{
setTimeout(function() {
$('.message_box').html(data);
}, delay);
}
});
});
</script>
<script>
//Email Validation Function
function isValidEmailAddress(emailAddress) {
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return pattern.test(emailAddress);
};
</script>
I've made a form in Ci which submits the data to the Db. I've been trying to implement validation in the form, For eg Name : more than 3+ Letters, email '#' Etc.
I never could seem to make it work, tried using Jquery validation with different sources , the form basically submits without Validation, Any pointers to where i'm going wrong?
The code below is just a snippet without any validation codes attached to it.
<button type="button" class="btn btn-info btn-lg btn-block" data-toggle="modal" data-target="#enquire">Enquire</button>
<div class="modal fade" id="enquire">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Enquire About "<?php echo $row_company->company_name; ?> "</h4>
</div>
<div class="modal-body">
<form name="reg_form" id="reg_form">
<div class="form-group">
<div class="input-group <?php echo (form_error('name')) ? 'has-error' : ''; ?>">
<label class="input-group">Your Name <span>*</span></label>
<input name="username" type="text" class="form-control" id="name" placeholder="Full Name" required="required" data-error="Name is required." maxlength="40">
<?php echo form_error('name'); ?>
</div>
<div class="input-group <?php echo (form_error('email')) ? 'has-error' : ''; ?>">
<label class="input-group">Email <span>*</span></label>
<input name="email" type="text" class="form-control" id="email" placeholder="Valid Email Id" required="required" maxlength="50">
<?php echo form_error('email'); ?>
</div>
<div class="input-group <?php echo (form_error('mobile')) ? 'has-error' : ''; ?>">
<label class="input-group">Mobile Number <span>*</span></label>
<input name="mobile" type="text" class="form-control" id="mobile" placeholder="Mobile" required="required" maxlength="50">
<?php echo form_error('mobile'); ?>
</div>
</div>
<input type="hidden" name="college" value='<?php echo $row_company->company_name; ?>'>
<p> <input id="click_form" value="submit" type="button" ></p>
</form>
<div class="ajax_success"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#click_form').click(function () {
var url = "<?php echo site_url('enquiry/ajax_post_form') ?>";
var data = $("#reg_form").serialize();
$.post(url, data, function (data) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}, "json");
});
});
</script>
</div>
</div>
</div>
</div>
Controller
public function ajax_post_form() {
$this->form_validation->set_rules('name', 'Your name', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|strip_all_tags');
$user_data = array(
'name' => $this->input->post('username'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'college' => $this->input->post('college')
);
$this->insert_model->form_insert($user_data);
$data['message'] = 'Data Inserted Successfully';
echo json_encode($user_data);
}
Model
function form_insert($user_data){
$this->db->insert('pp_enquiry', $user_data);
}
**Validation **
function checkForm() {
// Fetching values from all input fields and storing them in variables.
var name = document.getElementById("username1").value;
var email = document.getElementById("email1").value;
var mobile = document.getElementById("mobile").value;
//Check input Fields Should not be blanks.
if (name == '' || email == '' || mobile == '') {
alert("Fill All Fields");
} else {
//Notifying error fields
var username1 = document.getElementById("username");
var email1 = document.getElementById("email");
var mobile = document.getElementById("mobile");
//Check All Values/Informations Filled by User are Valid Or Not.If All Fields Are invalid Then Generate alert.
if (username1.innerHTML == 'Must be 3+ letters' || email1.innerHTML == 'Invalid email' || mobile.innerHTML == 'Invalid website') {
alert("Fill Valid Information");
} else {
//Submit Form When All values are valid.
document.getElementById("myForm").submit();
}
}
}
// AJAX code to check input field values when onblur event triggerd.
function validate(field, query) {
var xmlhttp;
if (window.XMLHttpRequest) { // for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState != 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = "Validating..";
} else if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(field).innerHTML = xmlhttp.responseText;
} else {
document.getElementById(field).innerHTML = "Error Occurred. <a href='index.php'>Reload Or Try Again</a> the page.";
}
}
xmlhttp.open("GET", "validation.php?field=" + field + "&query=" + query, false);
xmlhttp.send();
}
Please check here is the working example of your above code. I think you missed something in your code.
$(document).ready(function() {
var $validator = $("#reg_form").validate({
rules: {
name: {required: true, minlength: 3, maxlength: 25},
email: {required: true, email: true, minlength: 3, maxlength: 100, regex: /^[A-Za-z0-9_]+\#[A-Za-z0-9_]+\.[A-Za-z0-9_]+/},
mobile: {required: true, minlength: 10, maxlength: 12, number: true}
},
messages: {
email: {required: "Please enter valid Email Address"},
mobile: {required: "Please provide valid Phone or Mobile number!"}
}
});
jQuery.validator.addMethod("regex", function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
}, "Please provide valid email address.");
$('#click_form').click(function(e) {
e.preventDefault();
var $valid = $("#reg_form").valid();
if (!$valid) {
$validator.focusInvalid();
return false;
} else {
var url = 'https://www.example.com';
var data = $("#reg_form").serialize();
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function() {
console.log(data);
},
success: function(returnData) {
if (returnData.status) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<button type="button" class="btn btn-info btn-lg btn-block" data-toggle="modal" data-target="#enquire">Enquire</button>
<div class="modal fade" id="enquire">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Enquire About "Company Name"</h4>
</div>
<div class="modal-body">
<form name="reg_form" id="reg_form">
<div class="form-group">
<div class="input-group <?php echo (form_error('name')) ? 'has-error' : ''; ?>">
<label class="input-group">Your Name <span>*</span></label>
<input name="username" type="text" class="form-control" id="name" placeholder="Full Name" required="required" data-error="Name is required." maxlength="40">
<?php echo form_error('name'); ?>
</div>
<div class="input-group <?php echo (form_error('email')) ? 'has-error' : ''; ?>">
<label class="input-group">Email <span>*</span></label>
<input name="email" type="text" class="form-control" id="email" placeholder="Valid Email Id" required="required" maxlength="50">
<?php echo form_error('email'); ?>
</div>
<div class="input-group <?php echo (form_error('mobile')) ? 'has-error' : ''; ?>">
<label class="input-group">Mobile Number <span>*</span></label>
<input name="mobile" type="text" class="form-control" id="mobile" placeholder="Mobile" required="required" maxlength="50">
<?php echo form_error('mobile'); ?>
</div>
</div>
<input type="hidden" name="college" value='<?php echo $row_company->company_name; ?>'>
<p> <input id="click_form" value="submit" type="button" ></p>
</form>
<div class="ajax_success"></div>
</div>
</div>
</div>
</div>
You need to run the validation process as explained in the manual: https://www.codeigniter.com/user_guide/libraries/form_validation.html#the-controller
if ($this->form_validation->run() == FALSE)
You can find below mentioned solution.
PHP Validation
$this->form_validation->set_rules('name', 'Your name', 'trim|required|strip_all_tags|min_length[3]');
$this->form_validation->set_rules('email', 'Email', 'trim|required|strip_all_tags|valid_email|min_length[3]');
$this->form_validation->set_rules('mobile', 'Mobile', 'trim|required|strip_all_tags|min_length[10]|max_length[12]');
if ($this->form_validation->run() == FALSE) {
$data['status'] = false;
$data['error'] = validation_errors();
} else {
$user_data = array(
'name' => $this->input->post('username'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'college' => $this->input->post('college')
);
$this->insert_model->form_insert($user_data);
$data['status'] = true;
$data['message'] = 'Data Inserted Successfully';
}
echo json_encode($data);
jQuery Validation
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/additional-methods.min.js"></script>
$(document).ready(function() {
var $validator = $("#reg_form").validate({
rules: {
name: {required: true, minlength: 3, maxlength: 25},
email: {required: true, email: true, minlength: 3, maxlength: 100, regex: /^[A-Za-z0-9_]+\#[A-Za-z0-9_]+\.[A-Za-z0-9_]+/},
mobile: {required: true, minlength: 10, maxlength: 12, number: true}
},
messages: {
email: {required: "Please enter valid Email Address"},
mobile: {required: "Please provide valid Phone or Mobile number!"}
}
});
jQuery.validator.addMethod("regex", function(value, element, regexp) {
if (regexp.constructor != RegExp)
regexp = new RegExp(regexp);
else if (regexp.global)
regexp.lastIndex = 0;
return this.optional(element) || regexp.test(value);
}, "Please provide valid email address.");
$('#click_form').click(function(e) {
e.preventDefault();
var $valid = $("#reg_form").valid();
if (!$valid) {
$validator.focusInvalid();
return false;
} else {
var url = '<?php echo site_url('enquiry/ajax_post_form') ?>';
var data = $("#reg_form").serialize();
$.ajax({
url: url,
type: 'POST',
data: data,
dataType: 'json',
beforeSend: function() {
// Code if required before Send
},
success: function(returnData) {
if (returnData.status) {
$('.ajax_success').html('Enquiry Submitted Successfully!');
}
}
});
}
});
});
Let me know if it not works.
I am working on a sign up form, user shouldn't be allowed to register if username/email is taken.
so before inserting user info and accepting the sign up, I am checking 2 major conditions
1. If username is taken
2. If email is registered before
and then only the registration can go through.
I am using Ajax to send the data to php, but the data won't be inserted in the db for some reason (NO ERRORS SHOW!)
Where am I going wrong?
HTML code:
<form method="post" role="form" id="register-form" autocomplete="off" action="includes/check_signup.php">
<div class="form-header">
<h3 class="form-title"><i class="fa fa-user"></i><span class="glyphicon glyphicon-user"></span> Sign Up</h3>
<div class="pull-right">
<h3 class="form-title"><span class="glyphicon glyphicon-pencil"></span></h3>
</div>
</div>
<div class="form-body">
<!-- json response will be here -->
<div id="errorDiv"></div>
<!-- json response will be here -->
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-user"></span></div>
<input name="name" type="text" id="name" class="form-control" placeholder="Name" maxlength="40" autofocus="true" onBlur="checkname();">
</div>
<span class="help-block" id="error error-username"></span>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></div>
<input name="email" id="email" type="text" class="form-control" placeholder="Email" maxlength="50" onBlur="checkemail();">
</div>
<span class="help-block" id="error error-email"></span>
</div>
<div class="row">
<div class="form-group col-lg-6">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></div>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
</div>
<span class="help-block" id="error"></span>
</div>
<div class="form-group col-lg-6">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></div>
<input name="cpassword" type="password" class="form-control" placeholder="Retype Password">
</div>
<span class="help-block" id="error"></span>
</div>
</div>
</div>
<div class="form-footer">
<button type="submit" class="btn btn-info" id="btn-signup" name="signup">
<span class="glyphicon glyphicon-log-in"></span> Sign Me Up
</button>
</div>
<p id='result'></p>
</form>
Ajax code:
//check username availability
function checkname() {
jQuery.ajax({
url: "includes/check_signup.php",
data:'username='+$("#name").val(),
type: "POST",
success:function(data){
$("#error").html(data);
},
error:function (){}
});
}
function checkemail()
{
jQuery.ajax({
url: "includes/check_signup.php",
data:'email='+$("#email").val(),
type: "POST",
success:function(data){
$("#error").html(data);
},
error:function (){}
});
}
$('document').ready(function()
{
// name validation
var nameregex = /^[0-9a-zA-Z]+$/;
$.validator.addMethod("validname", function( value, element ) {
return this.optional( element ) || nameregex.test( value );
});
// valid email pattern
var eregex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
$.validator.addMethod("validemail", function( value, element ) {
return this.optional( element ) || eregex.test( value );
});
$("#register-form").validate({
rules:
{
name: {
required: true,
validname: true,
minlength: 4
},
email : {
required : true,
validemail: true,
remote: {
url: "check-email.php",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
},
password: {
required: true,
minlength: 5,
maxlength: 15
},
cpassword: {
required: true,
equalTo: '#password'
},
},
messages:
{
name: {
required: "Username is required",
validname: "Username can be a combination of Alphabets & Numbers",
minlength: "your username is too short"
},
email : {
required : "Email is required",
validemail : "Please enter valid email address",
remote : "Email already exists"
},
password:{
required: "Password is required",
minlength: "Password at least have 5 characters"
},
cpassword:{
required: "Retype your password",
equalTo: "Password did not match !"
}
},
errorPlacement : function(error, element) {
$(element).closest('.form-group').find('.help-block').html(error.html());
},
highlight : function(element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
},
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-group').find('.help-block').html('');
},
submitHandler: submitForm
});
});
$('#register-form').submit(function(){
return false;
});
$('#btn-signup').click(function(){
$.post(
$('#register-form').attr('action'),
$('#register-form :input').serializeArray(),
function(result){
$('#result').html(result);
}
);
});
PHP code:
<?php
function name (){
global $connection;
if(isset($_POST['username']))
{
$name=$_POST['username'];
$checkdata="SELECT * FROM users WHERE userName='$name' ";
$query=mysqli_query($connection, $checkdata);
if(mysqli_num_rows($query)>0)
{
echo "User Name is taken";
return true;
}
exit();
}
}
function email () {
global $connection;
if(isset($_POST['email']))
{
$emailId=$_POST['email'];
$checkdata=" SELECT * FROM users WHERE userEmail='$emailId' ";
$query=mysqli_query($connection, $checkdata);
if(mysqli_num_rows($query)>0)
{
echo "Email Already Exist";
return true;
}
exit();
}
}
function insert_db (){
global $connection;
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$pass = trim($_POST['cpassword']);
$full_name = strip_tags($name);
$user_email = strip_tags($email);
$user_pass = strip_tags($pass);
// sha256 password hashing
$hashed_password = hash('sha256', $user_pass);
$query = "INSERT INTO users(userName,userEmail,userPassword) VALUES('$name', '$email', '$hashed_password')";
$result = mysqli_query ($connection, $query);
if ($result) {
echo "You have been registered";
return true;
} else {
die ("error". mysqli_error ($connection));
}
}
if (name()) {
} elseif (email()) {
} else {
insert_db;
}
Maybe because you're closing php tag and the code after it's never going to be executed.
<?php include "config.php"; ?> function name (){
You're exiting the script when calling function name() when there is no result in db, just use a return false; instead of exit();
if(mysqli_num_rows($query)>0)
{
echo "User Name is taken";
return true;
}
return false;
Remove all the exit() from the script first of all, and replace it with return false.
if (name()) { #this will return false
} elseif (email()) { #after you removed exit() this should return false
} else {
insert_db(); #fix the call
}
I am trying to validate my form and insert the data in mysql database using ajax.Neither on submit validation is happening nor data is being inserted.I am making this in codeigniter framework. I am new bie to ajax.I am not able to figure out where am going wrong .Here is my code
View :
<script type="text/javascript">
function validate_name(first_name){
if(first_name.trim() == '' || first_name.length == 0){
$('.first_name').show();
$('.first_name').text('Please enter your name');
return false;
} else {
$('.first_name').hide();
return true;
}
}
function validate_email(email_id){
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
if(email_id.trim() == '' || email_id.length == 0){
$('.email-id').show();
$('.email-id').text('Please enter email address');
return false;
}else if(!pattern.test(email_id)) {
$('.email-id').show();
$('.email-id').text('Please enter valid email address');
return false;
} else {
$('.email-id').hide();
return true;
}
}
function validate_inquiry_form(first_name,email_id){
var username_validate = validate_name(first_name);
var email_validate = validate_email(email_id);
if(username_validate == true && email_validate == true){
return true;
} else {
return false;
}
}
$('#submit_enquiry').click(function(){
var first_name = $("input[name=first_name]").val();
var last_name = $("input[name=last_name]").val();
var dob = $("input[name=dob]").val();
var gender = $("input[name=gender] :radio:checked").val();
var email_id = $("input[name=email_id]").val();
var password = $("input[name=password]").val();
var address = $("input[name=address]").val();
var phone = $("input[name=phone]").val();
var zipcode = $("input[name=zipcode]").val();
var validate_form = validate_inquiry_form(first_name,email_id);
if(validate_form == true){
$.ajax({
url:'<?php echo base_url(); ?>member/register',
type:'POST',
data:{
first_name : first_name ,last_name : last_name ,dob : dob ,male : male ,female : female , email_id : email_id ,password : password ,phone : phone , address : address , zipcode : zipcode
},
success: function(data) {
console.log(data);
}
});
} else {
return false;
}
return false;
});
</script>
<form id="registration-form">
<div class="register">
<div class="row">
<div class="col1">
<label for="first_name">First Name<span>*</span></label> <br/>
<input type="text" name="first_name"/>
<li class="first_name error"></li>
</div>
<div class="col2">
Last Name<br/>
<input type="text" name="last_name"/>
</div>
</div>
<div class="row">
<div class="col1">
Date Of Birth <br/>
<input type="text" name="dob"/>
</div>
<div class="col2">
Gender
<br/>
<input type="radio" name="gender" value="Male" /> Male
<input type="radio" name="gender" value="Female" /> Female
</div>
</div>
<div class="row">
<div class="col1">
Email<br/>
<input type="text" name="email_id"/>
<li class="email-id error"></li>
</div>
<div class="col2">
Password<br/>
<input type="password" name="password"/>
</div>
</div>
<div class="row">
<div class="col">
Address<br/>
<textarea name="address" rows="2" ></textarea>
</div>
</div>
<div class="row">
<div class="col1">
Zipcode<br/>
<input type="text" name="zipcode"/>
</div>
<div class="col2">
Phone<br/>
<input type="text" name="phone"/>
</div>
</div>
<div class="row">
<div class="col3">
<input class="" type="button" id="submit_enquiry" name="submit_enquiry" value="Submit Enquiry" />
</div>
</div>
</div>
</form>
Controller:
public function register_user()
{
$register_user = $this->member_model->add_user();
if($register_user)
{
return true;
}
else
{
return false;
}
}
Model :
public function add_user()
{
$add_user = array(
'mem_name'=> $this->input->post('first_name'),
'mem_lastname'=> $this->input->post('last_name'),
'mem_dob'=> $this->input->post('dob'),
'mem_gender'=> $this->input->post('gender'),
'mem_email'=> $this->input->post('email_id'),
'mem_address'=> $this->input->post('address'),
'mem_zipcode'=> $this->input->post('zipcode'),
'mem_phone'=> $this->input->post('phone'),
'mem_password'=> $this->input->post('password'),
);
$insert = $this->db->insert('membership', $add_user);
$insert_id = $this->db->insert_id();
return $insert_id;
}
Please help me ....
change in this in your ajax add apostrophe (')
data:{
'first_name' : first_name ,'last_name' : last_name ,'dob' : dob , etc...
},
add this in your controler member
function register(){
$add_user = array(
'mem_name'=> $this->input->post('first_name'),
'mem_lastname'=> $this->input->post('last_name'),
'mem_dob'=> $this->input->post('dob'),
'mem_gender'=> $this->input->post('gender'),
'mem_email'=> $this->input->post('email_id'),
'mem_address'=> $this->input->post('address'),
'mem_zipcode'=> $this->input->post('zipcode'),
'mem_phone'=> $this->input->post('phone'),
'mem_password'=> $this->input->post('password'),
);
$this->member_model->add_user($add_user);
}
in your member_model
function add_user($add_user){
$insert = $this->db->insert('membership', $add_user);
}
You can use jquery validate and use ajay on submit handler. Please try following code:
$(function () {
$("#FormId").validate({
errorElement: 'span', errorClass: 'help-block',
rules: {
Tag: {
required: true
},
Table: {
required: true
},
Field: {
required: true
},
},
messages: {
Tag: {
required: "Tag is required."
},
Table: {
required: "Table is required."
},
Field: {
required: "Field is required."
},
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
success: function (element) {
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-group').children('span.help-block').remove();
},
errorPlacement: function (error, element) {
error.appendTo(element.closest('.form-group'));
},
submitHandler: function (form) {
$("#saveButton").button('loading');
$.post('', $("#FormId").serialize(), function (data) {
//Write your code here
});
}
});
});```
The problem with my form is that when i fill in everything correctly and the submit button doesn't do anything. My jQuery validation code are 100% working and i think the problem is at my php code. i JUST wonder if anyone can tell me the problem then i can fix it. If you want to see my jquery validation script its at here
:/
html core
<div id="registerForm">
<h1>Register</h1>
<form action="core/register.php" method="POST" class="registerForm form-horizontal">
<div class="form-group has-feedback">
<label class="control-label col-sm-2" for="username">Username:</label>
<div class="col-sm-10">
<span></span>
<input type="text" name="username" class="form-control" id="username" placeholder="Enter a username">
</div>
</div>
<div class="form-group has-feedback">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-10">
<span></span>
<input id="email" type="email" name="email" class="form-control" placeholder="Enter your email - IMPORTANT">
</div>
</div>
<div class="form-group has-feedback">
<label class="control-label col-sm-2" for="password">Password:</label>
<div class="col-sm-10">
<span></span>
<input id="password" type="password" name="password" class="form-control" placeholder="Enter a password">
</div>
</div>
<div class="form-group has-feedback">
<label class="control-label col-sm-2" for="confirmpassword">Confirm:</label>
<div class="col-sm-10">
<span></span>
<input id="confirmpassword" type="password" name="confirmpassword" class="form-control" placeholder="Confirm password">
</div>
</div>
<div class="form-group has-feedback">
<label class="control-label col-sm-2" for="code">Code:</label>
<div class="col-sm-10">
<span></span>
<input type="text" id="code" name="code" class="form-control" placeholder="Enter Register Code">
</div>
</div>
<div class="buttonspecial">
<input class="btn btn-primary" type="submit" id="submit" value="Register!">
</div>
</form>
</div>
And my php code:
//FUNCTION
function register($register_data, $mysqli) {
$username = $register_data['username'];
$password = crypt($register_data['password'], PASSWORDSTRING);
$email = $register_data['email'];
$email_code = $register_data['email_code'];
if ($insert_stmt = $mysqli->prepare("INSERT INTO users (username, password, email, email_code, created) VALUES (?, ?, ?, ?, NOW())")){
$insert_stmt->bind_param('ssss', $username, $password, $email, $email_code);
if ($insert_stmt->execute()) {
return true;
}
return false;
}
}
//WHERE FORM WILL BE SUBMITTED TO
<?php
include_once("../core/init.php");
if (isset($_POST['username'], $_POST['email'], $_POST['password'])){
$register_data = array(
'username' => $_POST['username'],
'password' => $_POST['password'],
'email' => $_POST['email'],
'email_code' => md5($_POST['username'] + microtime() + $_POST['email']),
);
if (register($register_data, $mysqli) == true){
header('Location: ../register_success.php');
} else {
header('Location: ../error.php?err=Registration failure: INSERT');
}
}
?>
jquery Validation code:
$(document).ready(function () {
$('.registerForm').validate({
// errorPlacement: function(error,element) {
// return true;
// },
rules: {
username: {
required: true,
rangelength: [5, 20],
remote: {
url: 'core/check/check.php',
type: "post",
data: {
username: function () {
return $("#username").val();
}
}
}
},
password: {
required: true,
rangelength: [5, 50]
},
confirmpassword: {
required: true,
rangelength: [5, 50],
equalTo: password
},
email: {
required: true,
remote: {
url: 'core/check/check.php',
type: "post",
data: {
email: function () {
return $("#email").val();
}
}
}
},
code: {
required: true,
remote: {
url: 'core/check/check.php',
type: "post",
data: {
code: function () {
return $("#code").val();
}
}
}
},
},
messages: {
username: {
required: "Enter a username.",
rangelength: "Username must be 5 to 20 character",
remote: "Username have been taken"
},
password: {
required: "Enter a password.",
rangelength: "Password must be 5 to 50 character",
remote: "Email have been taken"
},
confirmpassword: {
required: "Confirm your password.",
rangelength: "Password must be 5 to 50 character",
equalTo: "Your password does not match"
},
email: {
required: "Enter your email(NOT SPAM EMAIL).",
remote: "This Email have been taken"
},
code: {
required: "Enter your Register Code",
remote: "Invalid code or used code"
},
recaptcha_response_field: {
required: "Do the reCaptcha",
remote: 'Bad reCaptcha'
}
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('has-success').addClass('has-error').find('.col-sm-10 span').removeClass('glyphicon glyphicon-ok form-control-feedback').addClass('glyphicon glyphicon-remove form-control-feedback');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error').addClass('has-success').find('.col-sm-10 span').removeClass('glyphicon glyphicon-remove form-control-feedback').addClass('glyphicon glyphicon-ok form-control-feedback');
},
submitHandler: function () {
form.submit();
}
});
});
check.php
<?php
include_once("../core/connect/db_connect.php");
// EMAIL
if (isset($_POST['email'])){
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
$pre_stmt = "SELECT email FROM users WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($pre_stmt);
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
// CHECK IF EMAIL EXIST
if ($stmt->num_rows == 0){
echo "true";
$stmt->close();
} else {
echo "false";
$stmt->close();
}
}
}
// CODE
if (isset($_POST['code'])){
$ccode = filter_input(INPUT_POST, 'code', FILTER_SANITIZE_STRING);
$code = md5(trim(strtolower($ccode)));
$pre_stmt = "SELECT code FROM code WHERE code = ? AND used = 0";
$stmt = $mysqli->prepare($pre_stmt);
if ($stmt) {
$stmt->bind_param('s', $code);
$stmt->execute();
$stmt->store_result();
// CHECK IF CODE EXIST
if ($stmt->num_rows == 1){
echo 'true'; //OKAY
$stmt->close();
} else {
echo 'false'; //NOTOK
$stmt->close();
}
}
}
// USERNAME
if (isset($_POST['username'])){
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$pre_stmt = "SELECT username FROM users WHERE username = ?";
$stmt = $mysqli->prepare($pre_stmt);
if ($stmt) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
// CHECK IF CODE EXIST
if ($stmt->num_rows == 0){
echo 'true';
$stmt->close();
} else {
echo 'false';
$stmt->close();
}
}
}
?>
Here is your problem...
submitHandler: function () {
form.submit();
}
You forgot to pass the form argument into the function. The submitHandler takes over and prevents the native form submit; and it can't do anything with form.submit() since the form does not exist here. It should look more like this...
submitHandler: function (form) { // <- need to pass the 'form' argument here
$(form).submit();
}
HOWEVER, since a .submit() of the native form action is just what the plugin would already do by default, you do not need the submitHandler at all. The whole thing is superfluous. Remove it. Remove the entire submitHandler option.
(The submitHandler is only needed when you want to do something else, like submit the entire form via ajax().)
NOTES:
Your remote method is using the data option...
rules: {
username: {
// other rules,
remote: {
url: 'core/check/check.php',
type: "post",
data: {
username: function () {
return $("#username").val();
}
}
}
}, ....
The data option is not needed for the username field, because the value of this field is already sent by default with remote.
rules: {
username: {
// other rules,
remote: {
url: 'core/check/check.php',
type: "post"
}
}, ....
(The data option would only be needed if you wanted to send some other additional data along with this remote request.)
You have even more superfluousness here...
password: {
required: true,
rangelength: [5, 50]
},
confirmpassword: {
required: true,
rangelength: [5, 50],
equalTo: password
},
When using the equalTo rule, it mandates that the confirmpassword field exactly match the password field. This means that you could not leave confirmpassword blank or put in the wrong number of characters because it already must match the password field.
This will work practically the same...
password: {
required: true,
rangelength: [5, 50]
},
confirmpassword: {
required: true, // <- I left this one for an initial empty form
equalTo: password
},
BTW: You can simply use the placeholders within your error messages. The correct values will get inserted dynamically.
rangelength: "Username must be {0} to {1} characters",
Your DEMO: http://jsfiddle.net/2jwja5uy/1/
Same DEMO with remote methods removed so you can see it fire the submit: http://jsfiddle.net/2jwja5uy/2/