Email validation using JQuery Ajax

Viewed 23794

I've been having a hard time trying to validate an email with ajax using PHP and Javascript. What I want to do, is to check if the email already exists in the database, if so, display a message and then go back to the form, otherwise display a success message and close the form. The problem is that if the email exists it is displaying the "error message" and then displays the success message. I've checked similar questions and tried the code in them but none of them applied correctly to my requirements. Thank you.

Here's what I've got:

// JavaScript Document
$('#btnSubmit').click(function(){
    if(  validateForm() ){
        // code to submit all the info, display the success message and close the form
    }
    else return false;
});


// I created a function to validate all the fields in the form
function validateForm() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var email = $('#txtMail').val();

    // to validate firstName and lastName I do it like this:
    if(!firstName || firstName.length === 0) {
        message = "All fields are mandatory\\nFirst Name is required";
        messageDialog("Warning", message, "warning", 2);
        return false;
    } 
    if( !firstName.match(letters) ) {
        message = "Invalid name";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    // So far, no problem at all. But when I tried to validate email:
    else {
        // use ajax to check if a user has been previously registered
        // using this email
        $.ajax({
            url:"check_user.php",   // url that will use
            data:{                  // data that will be sent
                email:email
            },
            type:"POST",            // type of submision
            dataType:"text",        // what type of data we'll get back
            success:function(data)
            {    
                // if check_user returns a number different than 0
                // means that there's already a user registered with that email
                if(data > 0 ) {
                    message = "This email is registered already!";
                    messageDialog("Error", message, "error", 2);
                    return false;                   
                 }
                 else { return true;}
            }
        });

    }

    // if everything is right then return true so the submit function continue its execution
    return true;
}
3 Answers

You perform an ajax request, which by default is asynchronous, which means it doesn't wait for the response of your request before doing the rest of your function.

So in your case, once the request is made, it will return true as stated as the end of your function. Then, when the response of your ajax request comes back, it will trigger your success function, which will display the error message.

You can do something like that, using the async parameter of the $.ajax function to make sure that it will wait for the response of your request before going any further.

function validateForm() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var email = $('#txtMail').val();

    // to validate firstName and lastName I do it like this:
    if(!firstName || firstName.length === 0) {
        message = "All fields are mandatory\\nFirst Name is required";
        messageDialog("Warning", message, "warning", 2);
        return false;
    } 
    if( !firstName.match(letters) ) {
        message = "Invalid name";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    // So far, no problem at all. But when I tried to validate email:
    else {
        // use ajax to check if a user has been previously registered
        // using this email
        var valid = false;
        $.ajax({
            url:"check_user.php",
            async: false,
            data:{                  // data that will be sent
                email:email
            },
            type:"POST",            // type of submision
            dataType:"text",        // what type of data we'll get back
            success:function(data)
            {    
                // if check_user returns a number different than 0
                // means that there's already a user registered with that email
                if(data == 0 ) {
                    valid = true;
                }
            }
        });
        if(!valid) {
             message = "This email is registered already!";
             messageDialog("Error", message, "error", 2);
             return false;
        } else { return true; }
    }
    }

I don't see any success message, but I assume that your validate() function returns true when the e-mail address already exists.

This is caused by the fact that your ajax call is asynchronous and is not yet finished when your validate() function finishes. Apart from that what your return from your anonymous success function, is not what is returned from your ajax call; you don't even use the return value from your ajax call.

You can either make your ajax call synchronous and use a variable to set the return value from it or you can return the return value of your ajax call as well and continue processing when the ajax call is finished.

In Ajax call the success function is async that means your function will return always true if it arrive to check your email.

to correct this, you have to remove return true from your last else and inside success function call a function that will close your form like this :

// JavaScript Document
$('#btnSubmit').click(function(){
    if(  validateForm() ){
        // code to submit all the info, display the success message and close the form
    }
    else return false;
});


// I created a function to validate all the fields in the form
function validateForm() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var email = $('#txtMail').val();

    // to validate firstName and lastName I do it like this:
    if(!firstName || firstName.length === 0) {
        message = "All fields are mandatory\\nFirst Name is required";
        messageDialog("Warning", message, "warning", 2);
        return false;
    } 
    if( !firstName.match(letters) ) {
        message = "Invalid name";
        messageDialog("Warning", message, "warning", 2);
        return false;
    }
    // So far, no problem at all. But when I tried to validate email:
    else {
        // use ajax to check if a user has been previously registered
        // using this email
        $.ajax({
            url:"check_user.php",   // url that will use
            data:{                  // data that will be sent
                email:email
            },
            type:"POST",            // type of submision
            dataType:"text",        // what type of data we'll get back
            success:function(data)
            {    
                // if check_user returns a number different than 0
                // means that there's already a user registered with that email
                if(data > 0 ) {
                    message = "This email is registered already!";
                    messageDialog("Error", message, "error", 2);
                    return false;                   

                 } else {
                   // code to submit all the info, display the success message and close the form
                 yourfunctiontocloseyourform()
                 }
            }
        });
        return false;

    }

}
Related