Search code examples
javascriptform-submitemail-validation

checking an email uniqueness before submitting a sign up form


I've got trouble with checking an email uniqueness in the client side before submitting a sign up form to the server side.

submitButton.onclick = function(){
    var email = $('input[name = "email"]').val();
    var checkEmail;
    $.ajax({
        url: 'serverScripts/settings/checkEmailAvailability.php',
        data: {email: email},
        async: false,
        success: function(text){
            checkEmail = text;//Return "occupied" or "freeToUse"
        }
    });
    if(checkEmail == 'occupied'){
        return false;
    }
}

Solution

  • I decided to do that script correctly:

    <!DOCTYPE html>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <form action="javascript:alert('it went though pipes')" method="get">
    <input type="email" name="email">
    <input type="submit" name="submitButton" id="submitButton">
    </form>
    <script>
    $('form').submit(function(){
        var email = $('input[name = "email"]').val();
        var checkEmail = $.ajax({
            url: 'serverScripts/settings/checkEmailAvailability.php',
            data: {email: email},
            async: false,
            success: function(data) {
                result = data;
            }
        });
        if(result.search('occupied')!=-1){
            alert("You've done something WRONG");
            return false;
        }
    })
    </script>
    

    Now maybe some explanation. It uses jQuery. The <form action="..."> is just for fun, replace it will real address and feel free to insert <form> into real page. Now what was wrong? text is reserved in JS, you cannot use it, so I changed it to data. Also, I decided to use .search while searching for "occupied" and change the method which you use onsubmit a little :P.

    I made quick testing page, if you're interested: (the only accepted is [email protected] if you want to know).

    http://glitchmr.pl/nuda/test.html

    (also, $.ajax is specific to jQuery, if you don't use it already)