0

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

Lucas
  • 9,871
  • 5
  • 42
  • 52
user3191005
  • 41
  • 1
  • 7
  • possible duplicate of [Jquery: return: false on submit not working - form still submits](http://stackoverflow.com/questions/18335408/jquery-return-false-on-submit-not-working-form-still-submits) – Ryan Jan 15 '14 at 16:52

3 Answers3

1

You are trying to make the result of a function dependent on the return value of an Ajax call you make from that function.

Ajax is asynchronous, so you cannot do that.

Instead, run the Ajax that tests the if the entered data is OK when the change event for that field fires. Store the result somewhere (possibly in a data attribute on the element). Remove that results as soon as the data is changed again (but put it back when the new Ajax response arrives)

You will then have one of the following situations:

Field marked as invalid so you can just return false from your normal validation routine.

Field marked as valid (and is valid) so you can return true and submit normally.

Field marked as valid (and is invalid) because the Ajax request is still in flight in which case, submit normally and let your server side validation catch the problem.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

I looked at your code and found that you are not doing asynch:false in your jquery while validating your email.

asych:false //make request synchronous

asynch:false means statement which is executing now have to complete in order to control go to next statement.

-1

Add preventDefault() to your submit so it ignores the original submit behavior.

So where your code is this:

 $("#signup").submit(function(event){
      event.preventDefault(); // <-- add this

Now that your default submit behavior is disabled, you can call your post form through ajax. So once everything is validated, you simple just call this:

$.post( 'myurl.php' , $this.serialize() ,  function( data ) {
       //return data once post (submit) is complete

    });

Or you can restructure your code, and place all of your validation inside of a function. Like this:

function validateFields() {
  if (fname==0){return false;}
  //place all your validation including ajax here
  return true;
}

Then in your form, simply do this:

<form onSubmit="return validateFields()">

That way if your function returns false (in other words a validation error), then it will not submit the form.

Control Freak
  • 12,965
  • 30
  • 94
  • 145