3

I am using AJAX to call a PHP file that does email validation and outputs simple text that gets returned to the AJAX Success. I am using the text returned to create variables to represent which error to display. I am having trouble using these variables, the form still submits. What could I be doing wrong?

My Code:

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,
    success: function(data) {
        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;
}
user3191005
  • 41
  • 1
  • 7

2 Answers2

1

Is this AJAX call inside a click event? If so, you may want to use event.preventDefault() function to avoid triggering the form submission:

event.preventDefault();

Have a look to the example in the documentation

dcapilla
  • 171
  • 6
0

You should have two things in consideration:
1) if you're ajax call is triggered by a link or submit button , you MUST use preventDefault function
2) in your "checkmail.php" don't forget to call exit function in the end of call

KB9
  • 599
  • 2
  • 7
  • 16