0

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;
        }
    }
    });
}

    });
2
  • async is spelled wrong in your code. And it is the not proper way to do it Commented Jan 16, 2014 at 14:31
  • You are checking if the email is not equal 0. Try email.length != 0 as a first step. Also is good to run the validation before you get into the ajax block. Try using regex for the email. If it passes run the post block if not return an error Commented Jan 16, 2014 at 14:32

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.