user3191005
user3191005

Reputation: 41

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.

My Code:

$("#signup").submit(function() {

var error= false;

var dataString = $(this).serialize();
var email= $("#email").val().trim();


if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
    $.ajax({  
    type: "POST",  
    url: "checkemail.php",  
    data: dataString,
        async: false,
    success: function(data) {
        var error= false;

        if (data == 'invalid') {
        var invalid= 1;
        }
        else if (data == 'taken') {
        var taken= 1;
        }
        if (invalid == 1) {
        alert('invalid email');
            error = true;
        }
        if (taken == 1) {
        alert('email taken');
        error = true;
        }
        if (error == true) {
        return false;
        }
    }
    });
}

    });

Upvotes: 0

Views: 123

Answers (2)

asprin
asprin

Reputation: 9823

If you absolutely have to use AJAX for form submission, this might be a better way to do it:

$('form').submit({

      $.ajax({
           type:'post',
           url: 'someurl.php',
           data: dataString,
           context: this, // this here refers to the form object
           success:function(data)
           {
               // perform your operations here
               if(something_is_wrong)
               {
                   // show message to user
               }
               else
               {
                    this.submit(); // put this code in the block where all is ok
               }

           }
      });

    return false; // makes sure the form doesn't submit

});

Upvotes: 0

Jai
Jai

Reputation: 74738

Try updating these:

$("#signup").submit(function(e) {  //<----pass the event here as "e"
    e.preventDefault();  //<----stops the form submission
    var error= false;

    var dataString = $(this).serialize();
    var email= $.trim($("#email").val());  //<----use trim this way

Upvotes: 2

Related Questions