Validation in Jquery ajax form submission - javascript

I am trying to validate user to enter a unique mobile number and email id.
It is checking and showing result mobile/email exist or not but if it exists still the form is submitting. Since I am new to jQuery validation I am not able to figure out how I should do it correctly nor can I find a perfect tutorial to do it in a right way.
Here is my code, I know lots of mistakes would be there and I apologize for those small mistakes.
On my form I have given On blur function to check mobile number and email
From these two functions I am checking in database if exist or not
function check_availability() {
//get the mobile number
var main = $('#main').val();
//use ajax to run the check
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
}
});
}
function email_availability() {
//get the email
var main = $('#email_tuitor').val();
//$email = urldecode("[email]")
//use ajax to run the check
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
}
});
}
This is the jquery ajax form submission is it possible to do every validation on blur ?
$(document).ready(function() {
$('.error').hide();
$("#next_tutor").click(function() {
$('.error').hide();
var main = $("#main").val();
if (main == "") {
$("label#main_error").show();
$("input#main").focus();
return false;
}
var name = $("#name").val();
if (name == "") {
$("label#name_error").show();
$("input#name").focus();
return false;
}
var email_tuitor = $("#email_tuitor").val();
if (email_tuitor == "") {
$("label#email_tuitor_error").show();
$("input#email_tuitor").focus();
return false;
}
var password_tuitor = $("#password_tuitor").val();
if (password_tuitor == "") {
$("label#password_tuitor_error").show();
$("input#password_tuitor").focus();
return false;
}
var tutor = $("#tutor").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'main=' + main + '&name=' + name + '&email_tuitor=' + email_tuitor + '&password_tuitor=' + password_tuitor + '&tutor=' + tutor;
// AJAX Code To Submit Form.
//alert(dataString);
//die;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>tutor/tutor_sub_ses",
data: dataString,
cache: false,
success: function(result) {
//alert(result);
$("#abc").hide();
$("#tutorreg2").slideToggle("slow").show();
}
});
return false;
});
});
<form class="form-horizontal" action="#">
<div class="form-group">
<div class="col-sm-8 text-center">
<h2 class="text-warning">Tutor Registration</h2>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" value="tutor" style="display:none" id="tutor">
<input type="text" class="form-control" id="name" placeholder="Name">
<label id="name_error" class="error" for="name"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control phone" id="main" placeholder="Mobile Number *This will be the key to your account*" onBlur="check_availability()">
<span id="mobile_availability_result"></span>
<label id="main_error" class="error" for="main"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="text" class="form-control" id="email_tuitor" placeholder="Email" onBlur="email_availability()">
<span id="email_availability_result"></span>
<label id="email_tuitor_error" class="error" for="email_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8">
<input type="password" class="form-control" id="password_tuitor" placeholder="Password">
<label id="password_tuitor_error" class="error" for="password_tuitor"><small style="color: red;">This Field Is Required</small>
</label>
</div>
</div>
<div class="form-group">
<div class="col-sm-8 text-right">
<button type="submit" class="btn btn-warning" id="next_tutor">Next</button>
</div>
</div>
</form>

The quick way will be to use a global switch to enable sending the form. I would to it this way:
Create global variables with default values
var mobileApproved = false, emailApproved = false;
Check status and prevent sending if value is false in click handler
$(document).ready(function() {
...
$("#next_tutor").click(function() {
if (!mobileApproved || !emailApproved) {
return false;
}
...
})
...
})
In your check functions manage approved status after each ajax response
...
$.post("tutor/check_mobile", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#mobile_availability_result').html(' ');
mobileApproved = true;
} else {
//show that the username is NOT available
$('#mobile_availability_result').html('Mobile Number already registered ');
mobileApproved = false;
}
});
...
$.post("<?php echo base_url(); ?>tutor/check_email", {
main: main
},
function(result) {
//if the result is 1
if (result == 1) {
//show that the username is available
$('#email_availability_result').html(' ');
emailApproved = true;
} else {
//show that the username is NOT available
$('#email_availability_result').html('Email already registered ');
emailApproved = false;
}
});

In order to stop the form from submission. You can keep a flag lets say formvalid.
Keep formValid as false initially. Based on your blur function, make it true if email and mobile are available else keep it false. In your form submission, put an if condition to check , if formvalid is true or not. If true then process with form submission else stop and throw error.

Related

Error using ajax to check email from database

I've read the answers from several users here, and my intention is to check if the email is already on the DB.
So my code is the following
**HTML CODE**
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input id="fnam" name="firstname" class="profile-input form-control" type="text" placeholder="First Name" autocomplete="off" maxlength="25" required />
<!-- <input id="fullname" name="fullname" class="form-control" placeholder="Full Name" required="" type="text">-->
</div>
</div>
</div>
</fieldset>
<fieldset>
<!-- Prepended text Last Name-->
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input id="lastname" name="lastname" class="profile-input form-control" type="text" placeholder="Last Name" autocomplete="off" maxlength="25" required />
<!-- <input id="fullname" name="fullname" class="form-control" placeholder="Full Name" required="" type="text">-->
</div>
</div>
</div>
</fieldset>
<fieldset>
<!-- Prepended text Email-->
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
<input id="email" name="email" class="profile-input form-control" type="email" placeholder="Email" autocomplete="off" maxlength="50" required/>
<!-- <input id="email" name="email" class="form-control" placeholder="Email" required="" type="text">-->
</div>
</div>
</div>
JS/ AJAX
function chemail(inputText) {
var email1 = $("#email").val();
var x = document.forms["myappForm"]["email"].value;
var datastring = '$email='+ x; // get data in the form manual
//var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
// if(inputText.value.match(mailformat)){
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
var msgp="Invalid Email. Ex: abc#ggggg.com";
document.getElementById("msgreturn").style.color= "red";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "red";
document.myappForm.email.focus();
return false;
}
else
{
document.myappForm.email.focus();
var msgp="Email verified";
document.getElementById("msgreturn").style.color= "green";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "green";
return true;
$("span.loading").html("<img src='images/ajax_fb_loader.gif'>");
$("span.validation").html("");
var datastring = '&email='+ x;
$.ajax({
type: "POST", // type
url: "check_email.php", // request file the 'check_email.php'
data: datastring, // post the data
success: function(responseText) { // get the response
if(responseText == 1) { // if the response is 1
$("span.email_val").html("<img src='images/invalid.png'> Email are already exist.");
$("span.loading").html("");
} else { // else blank response
if(responseText == "") {
$("span.loading").html("<img src='images/correct.png'> You are registred.");
$("span.validation").html("");
$("form input[type='text']").val(''); // optional: empty the field after registration
}
}
}
}
}
and the check_email.php
<?php require_once("../../php_includes/dbconnect.php");
$email = $_POST['x'];
$query = mysql_query("SELECT 'email' FROM 'members' WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { echo '1'; } else { echo '1'; }
?>
So the sources are all working, I've set some alerts inside of ajax but it didn't worked, can you please tell me where am I making the mistake , I'm following the example from other users from this site, however can't reach a solution.
Assuming that you have directly copied your code, the error can be found by checking indentation. I would suggest, BTW, that you make your editor replace tabs with spaces, as tabs may not show the spacing correctly on any other system (such as SO!).
function chemail(inputText) {
var email1 = $("#email").val();
var x = document.forms["myappForm"]["email"].value;
var datastring = '$email='+ x; // get data in the form manual
//var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
// if(inputText.value.match(mailformat)){
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
var msgp="Invalid Email. Ex: abc#ggggg.com";
document.getElementById("msgreturn").style.color= "red";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "red";
document.myappForm.email.focus();
return false;
}
else
{
document.myappForm.email.focus();
var msgp="Email verified";
document.getElementById("msgreturn").style.color= "green";
document.getElementById("msgreturn").innerHTML = msgp;
document.getElementById("lem").style.color= "green";
return true;
// HERE'S THE PROBLEM!!! The following code never gets executed. Missing parenthesis.
$("span.loading").html("<img src='images/ajax_fb_loader.gif'>");
$("span.validation").html("");
var datastring = '&email='+ x;
$.ajax({
type: "POST", // type
url: "check_email.php", // request file the 'check_email.php'
data: datastring, // post the data
success: function(responseText) { // get the response
if(responseText == 1) { // if the response is 1
$("span.email_val").html("<img src='images/invalid.png'> Email are already exist.");
$("span.loading").html("");
} else { // else blank response
if(responseText == "") {
$("span.loading").html("<img src='images/correct.png'> You are registred.");
$("span.validation").html("");
$("form input[type='text']").val(''); // optional: empty the field after registration
}
}
}
}
} // <--- this parenthesis is in the wrong place.
Another thing that should tip you off to the problem is to use the Network tab in the web console. You can use this to see the traffic between the browser and the server; in this case, you would find that there was no request made to the PHP script.
Addendum:
I believe datastring should be an object, not an url encoding. In other words,
var datastring = {email: x};
where x = $('#email').val();
For what it's worth, since you're using JQuery for your ajax, it would be more concise to change things like
document.getElementById("msgreturn").style.color= "red"; to $('#msgreturn').css('color','red');

check username availability with jQuery

I am using this function to check username availability when registering, and if the username exist, the submit button is disabled. I'm using a php script to check if the username exists in the database. The code works perfectly in my local server, but when hosted on a Godaddy server, I get the below error when I submit or when I try to navigate to another page:
After the empty response, I can't access my website for about a minute and then it's fine.
I tried a lot of things like calling jquery.js file before all other js files, but nothing works for me.
I am not very good with jQuery and javascript. Thank you for your suggestions.
ere is the script and the HTML form :
function check_availability_username() {
var min_chars = 4;
var max_chars = 30;
var re = /^\w+$/;
var characters_error1 = 'Minimum amount of chars is 4';
var characters_error2 = 'Maximum amount of chars is 30';
var characters_error3 = 'Chars can be only letters, numbers and underscores!';
var checking_html = 'Checking...';
var username = $('#username').val();
$.post("check_username.php", {
username: username
},
function(result) {
if (result == 1) {
if ($('#username').val().length < min_chars) {
$('#username_availability_result').html(characters_error1);
$('input[name=submit]').attr('disabled', true);
} else if ($('#username').val().length > max_chars) {
$('#username_availability_result').html(characters_error2);
$('input[name=submit]').attr('disabled', true);
} else if (!re.test($('#username').val())) {
$('#username_availability_result').html(characters_error3);
$('input[name=submit]').attr('disabled', true);
} else {
$('#username_availability_result').html(username + ' is Available');
$('input[name=submit]').attr('disabled', false);
}
} else {
$('#username_availability_result').html(username + ' is not Available');
$('input[name=submit]').attr('disabled', true);
}
});
if (event.which == 13 || event.keyCode == 13) {
$.post("check_username.php", {
username: username
},
function(result) {
if (result == 0) {
$('#username_availability_result').html(username + ' is not Available');
$('input[name=submit]').attr('disabled', true);
}
});
}
$('#submit').click(function() {
$.post("check_username.php", {
username: username
},
function(result) {
if (result == 0) {
$('#username_availability_result').html(username + ' is not Available');
$('input[name=submit]').attr('disabled', true);
}
});
});
}
<form id="login-id" action="suscribe-form.php" method="POST" onkeyup="return check_availability_username();">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control button-or-space" name="username" id="username" value="" minlength="4" maxlength="25" required pattern="\w+">
<input type='hidden' id='check_username_availability' value='Check Availability'> <span id='username_availability_result' name='username_availability_result'></span>
</div>
<div class="form-group">
<label for="password1">Password</label>
<input type="password" class="form-control button-or-space" name="password1" id="password1" value="" minlength="8" maxlength="60" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" onchange="form.password2.pattern = this.value;">
</div>
<div class="form-group">
<label for="password2">Confirm password</label>
<input type="password" class="form-control button-or-space" name="password2" value="" minlength="8" maxlength="60" required pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}">
</div>
<div class="form-group pull-right">
<input type="submit" name="submit" id="submit" value="Register" class="btn btn-success button-or-space">
</div>
</form>
And here is the php script :
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db('DB');
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query('select username from user where username = "'.$username.
'"');
if (mysql_num_rows($result) > 0) {
echo 0;
} else {
echo 1;
}
?>
I finally found the solution. The problem was not from the jQuery or the php script, i only changed the way i call the function in the form from : onkeyup to onchange, and it is now working like a charm. I hope this tip avoid to others losing hours of time like it did to me. Thank's guys for your suggestions.
If you are getting 500 error that there is problem with the database connection.
check for the included files and connection variables used for database connection.
Hope that will work.

JavaScript reloads the complete page

I am using the following script to validate a registration form:
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should at least 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function(data) {
if (data == 'You have Successfully Registered.....') {
alert("Tu cuenta de usuario ha sido creada");
}
});
}
});
});
I am checking all possible options, and I have detected that the conditions are working, but instead of stopping the execution of the script, the page reloads itself after one condition is met. For example, if the password length is 6 characters, the alert:
alert("Password should at least 8 character in length...!!!!!!");
Is thrown, but the page reloads again and all text in the input fields are removed...
And also when the $.post call is executed and the response is the expected, the alert:
alert("Tu cuenta de usuario ha sido creada");
Is not shown.
The record is created in the database and the page reloads again, but the alert is not shown.
EDIT
This is the html part of the form:
<div class="form-bottom">
<form role="form" method="post" action="#" class="login-form" id="login_form">
<div class="form-group">
<label class="sr-only" for="form-username">Usuario</label>
<input type="text" name="dname" placeholder="Usuario..." class="form-username form-control" id="name">
</div>
<div class="form-group">
<label class="sr-only" for="form-email">Email</label>
<input type="text" name="email" placeholder="Email..." class="form-email form-control" id="email">
</div>
<div class="form-group">
<label class="sr-only" for="form-password">Contraseña</label>
<input type="password" name="password" placeholder="Contraseña..." class="form-password form-control" id="password">
</div>
<div class="form-group">
<label class="sr-only" for="form-confirm-password">Confirmar Contraseña</label>
<input type="password" name="cpassword" placeholder="Confirmar Contraseña..." class="form-password form-control" id="cpassword">
</div><br>
<button type="submit" name="register" id="register" class="btn">Crear cuenta de usuario</button>
</form>
may be your #register is a submit button and form is posting
In your HTML form change following button code
<button type="submit" name="register" id="register" class="btn">Crear cuenta de usuario</button>
to
<button type="button" name="register" id="register" class="btn">Crear cuenta de usuario</button>
Here is the fiddle
only thing that is changed is the type of button.
When you click the button it executes the default action for that button. Since your button has type submit, the default action is to submit the form. This is what you see in your application - you run the script, and then the form is submitted.
In order to prevent that you need to use method preventDefault on event object:
$("#register").click(function(e) { // <- pass event object as first parameter
e.preventDefault(); // <- call preventDefault to prevents form from submitting
var name = $("#name").val();
// the rest of your code
}
When you call this method the default action of the event will not be triggered. In your case this means that the form will not be submitted and your code should be working fine.
You need to return false at the end of click event
$(document).ready(function() {
$("#register").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var password = $("#password").val();
var cpassword = $("#cpassword").val();
if (name == '' || email == '' || password == '' || cpassword == '') {
alert("Please fill all fields...!!!!!!");
} else if ((password.length) < 8) {
alert("Password should at least 8 character in length...!!!!!!");
} else if (!(password).match(cpassword)) {
alert("Your passwords don't match. Try again?");
} else {
$.post("register.php", {
name1: name,
email1: email,
password1: password
}, function(data) {
if (data == 'You have Successfully Registered.....') {
alert("Tu cuenta de usuario ha sido creada");
}
});
}
return false; // put this it will solve your problem
});
});

I need to validate form data using JQuery before i can post it using PHP

Here is my form that i created using HTML and Bootstrap
<div class="col-sm-7 slideanim">
<form id="frm-post-comment" name="frm-post-comment" method="post" action="#">
<input type="hidden" name="the-comment" value="true">
<div class="row">
<div class="col-sm-6 form-group">
<input class="form-control" name="name" placeholder="Name" type="text">
</div>
<div class="col-sm-6 form-group">
<input class="form-control" name="email" placeholder="Email" type="email">
</div>
</div>
<textarea class="form-control" name="comments" placeholder="Comment" rows="5"></textarea>
<br>
<div class="row">
<div class="col-sm-12 form-group">
<button id="comment-post" class="btn btn-info pull-right" type="submit">Send</button>
</div>
</div>
</form>
</div>
I then want to validate the form inputs using JQuery, here is the validation code
$(document).ready(function() {
$("#comment-post").click(function() {
submitComment();
$("#comment-pst-alert").show();
$("html,body").animate({
scrollTop: 0
}, "slow");
});
});
function submitComment() {
var msg = "";
var name = $("#name").val();
var email = $("#email").val();
var comments = $("#comments").val();
var re = /^[A-Za-z]+$/;
if (name == "" || name.length < 3) {
msg += "*Please enter a valid name,it must be longer than three characters.<br>";
}
if (!re.test(name)) {
msg += "*Please enter a valid name,it must not contain numbers.";
}
var chkEmail = /^[a-z0-9._%-]+#[a-z0-9.-]+\.[a-z]{2,4}$/;
if (email == "") {
msg += "<br>*Please enter an email address.";
}
if (email.length < 8) {
msg += "<br>*Email address cannot be less than 8 characters";
}
if (email.search('#') == -1) {
msg += "<br>*Email must have a #,please enter a valid email address.";
}
if (comments == "") {
msg += "<br>*Please enter a comment.";
}
if (comments.length > 70) {
msg += "<br>*The comment can not exceed 70 characters";
}
if (msg != "") {
$("#comment-pst-alert").addClass("alert-danger");
$("#comment-pst-alert").children("strong").text("Warning");
$("#comment-pst-alert").children("p").html(msg);
}
else {
$("#name").val("");
$("#email").val("");
$("#comments").val("");
var closeAlert = $("<a/>", {
"class": "close",
"data-dismiss": "alert",
"text": "x"
});
$("#comment-pst-alert strong").before(closeAlert);
$("#comment-pst-alert").removeClass("alert-danger");
$("#comment-pst-alert").addClass("alert-success");
$("#comment-pst-alert").children("strong").text("Success");
msg += "<br>You have successfully submitted your details, you will here from us within 24 hours.";
$("#comment-pst-alert").children("p").html(msg);
}
$("#comment-pst-alert").show();
}
I have a bootstrap alert control that is initially hidden using CSS. If there is an error in the user input, I show the alert control and add the relevant class to it. If there is no error, I want to remove the former class and add a success class to the alert control and then I want to submit the input and add the data into the database using PHP.
$connection = mysql_connect('localhost', 'root', 'root');
if ($connection) {
if ($_POST["name"] != "" ||
$_POST["email"] != "" ||
$_POST["comments"] != "") {
mysql_select_db("smart_hustle_comments") or die("could not select table ".mysql_error());
$name = $_POST["name"];
$email = $_POST["email"];
$comment = $_POST["comments"];
$sql = "INSERT INTO user_comments VALUES('$name','$email','$comment')";
$query = mysql_query($sql);
}
}
I am getting no error on console nor on PHP,the form submits but does not execute the JQuery validation, please help.
Your jquery validation is skipped because you submit form simultaneously with validation.
Change your button type to button type instead submit, after successfull validation use $('#frm-post-comment').submit(); to apply form.

Can not return ajax responseText from a function in jquery

I have a form for user to register new account. I use jquery + ajax to check availability of email address on blur. In Jquery code I used e.preventDefault(); to prevent form submission if there is any error occurs. I tried the existed email address in the email input and click submit the form. It allows form to submit. It should not do this because ajax reponseText return false. Please anyone tell me what should I fix this code to work? I also read similiar article, i tried but still does not work. Please help me to point out what i need to fix my current code?
Here is my form:
<form role="form" method="post" id="signupForm" action="index.php?view=signup-gv">
<div class="col-xs-6 border-right">
<div class="form-group">
<label for="exampleInputEmail1">Full Name</label>
<input type="text" class="form-control" id="regname" name="regname" placeholder="Full Name">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email Address</label><span id="emailcheck"></span>
<input type="email" class="form-control" id="regemail" name="regemail" placeholder="Enter email">
</div>
</div>
<div class="form-group col-xs-6">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="regpass" name="regpass" placeholder="Password">
</div>
<button style="position:relative; left: 15px; top: 10px;" class="btn btn-default" name="register" id="register">Register</button>
</form>
Here my jquery code:
$(document).ready(function(){
$('#regname').focus();
$('#regemail').blur(emailCheck);
$('#signupForm').submit(function(e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
if(regname.val() == ''){
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
e.preventDefault();
}
else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
e.preventDefault();
}
else if (emailCheck()==false) {
regemail.focus();
register_result.html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
e.preventDefault();
}
else if(regpass.val() == ''){
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
e.preventDefault();
}
});
});
function emailCheck() {
var regemail = $('#regemail');
var emailcheck = $('#emailcheck');
emailcheck.html('');
var UrlToPass = {regemail:regemail.val()} ;
$.ajax({
type : 'POST',
cache: false,
data : UrlToPass,
url : 'emailcheck.php',
success: function(responseText){
if(responseText == 0){
return true;
}
else{
emailcheck.html('<span class="errorss"> This email is existed.</span>');
return false;
}
}
});
}
So, the problem is: you're trying to return from an asynchronous function. Your function emailCheck have already ended without returning anything when you try to return "true" or "false" inside your success callback function.
So when you declare a function submit, you should be aware of you can only go further with your submit after returning the ajax call. I would suggest you to always return false from your submit, and then, only inside your callback you decide if you submit your code or not. So here, you could something like this:
$('#signupForm').submit(function(e) {
var regname = $('#regname');
var regemail = $('#regemail');
var regpass = $('#regpass');
var register_result = $('#register_result');
register_result.html('Loading..');
if(regname.val() == ''){
regname.focus();
register_result.html('<span class="errorss"> * Full name can not be blank</span>');
return false;
} else if ($.trim(regemail.val()).length == 0) {
regemail.focus();
register_result.html('<span class="errorss">* Email address can not be blank</span>');
return false;
} else if(regpass.val() == ''){
regpass.focus();
register_result.html('<span class="errorss">* Password can not be blank</span>');
return false;
}
emailCheck().done(function(r){
if(r){
$('#regemail').focus();
$('#register_result').html('<span class="errorss"> This email address is already existed. Please choose another one </span>');
//Reseting to submit bind to not call function again
$('#signupForm').submit(function(){});
$('#signupForm').submit();
}
}).fail(function(r){
// Do something if fail.
});
return false
});
This is only a workaround for your problem. For more elegant solutions, you should check again the link you mentioned: How to return the response from an asynchronous call?. Especially, in the answer, the section Improving Bad Code
Another fix you should make, you should select your 'span' again using the same selector in your callback function. So, do this:
$('#emailcheck').html('<span class="errorss"> This email is existed.</span>');
instead of this:
emailcheck.html('<span class="errorss"> This email is existed.</span>');

Categories