I am using JQUERY to validate a signup form from the client side. I am also using an AJAX request with a PHP file to check and make sure that the email is a valid email and not already in use by another user. Everything works great except that it seems like the form submits before the AJAX success completes. Is this a common problem? How do I prevent this?
My JQUERY/AJAX:
<script>
$(document).ready(function() {
$(".form-row-error").hide();
$("#signup").submit(function() {
$(".form-row-error").hide();
var error= false;
var dataString = $(this).serialize();
var fname= $("#fname").val().trim();
var lname= $("#lname").val().trim();
var email= $("#email").val().trim();
var username= $("#username").val().trim();
var password1= $("#password1").val().trim();
var password2= $("#password2").val().trim();
if (fname == 0) {
$("#field1").show();
error= true;
}
if (lname == 0) {
$("#field2").show();
error= true;
}
if (email == 0) {
$("#field3").show();
error= true;
}
else {
// Run AJAX email validation and check to see if the email
is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
success: function(data) {
if (data == 'invalid') {
alert('invalid email');
error= true;
}
else if (data == 'taken') {
alert('email taken');
error= true;
}
}
});
}
if (username == 0) {
$("#field4").show();
error= true;
}
// Checks to see if the username is already in use, if so show the
field4 secondary error
if (username != 0) {
// Script to check the username against the database and
shows the error if applicable
// $("#field4-secondary").show();
// error= true;
}
if (password1 == 0) {
$("#field5").show();
error= true;
}
if (password2 == 0) {
$("#field6").show();
error= true;
}
// Checks and makes sure both password fields have been filled
if (password1 != 0 && password2 != 0) {
// Checks to see if the passwords match, if not show the
field5 secondary error and reset the password fields
if (password1 != password2) {
$("#field5-secondary").show();
$("#password1").val("");
$("#password2").val("");
error= true;
}
}
if (error == true) {
return false;
}
});
});
</script>
Some background:
The AJAX success alerts only have a chance to appear if I leave another field blank as well as have an error with the email. Which is what leads me to believe that the AJAX request does not have a chance to complete before the next part of the script begins.
My PHP file is not the issue.
I am not interested in Using JSON, I find that returning simple text is easier.
I am using JQuery 1.7.1