0

I am having a code that will check if the username is available in the database, the code can show an error message that the email is already exists but when I press the submit button it will insert the username in the database even if the username is already exists.

here is my code:

function validateForm(){
<script>
$(document).ready(function () {
    $("#Name").change(function () {
        var username = $("#Name").val();
        var msg = $("#msg");
        if (username.length > 2) {
            $("#msg").html('Checking availability');
            $.ajax({
                type: "POST",
                url: "check_availability.php",
                data: "Name=" + username,
                success: function (messagess) {
                    $("#msg").ajaxComplete(function (event, request) {
                        if (messagess.indexOf('OK') > 0) {
                            $("#Name").removeClass("exists");
                            $("#Name").addClass("avail");
                            msg.html('the user name is available</font>');
                        } else {
                            $("#Name").removeClass("avail");
                            $("#Name").addClass("exists");
                            msg.html('the user name is already exists');
                        }
                    });
                }
            });
        }
    });
});
}
</script>
</head>
<body>

<form action="" method="post" name="form" onsubmit="return validateForm()">    
User Email:&nbsp;
<input type="text" name="Name" id="Name" value="" />
<span id="msg"></span>
</form>
</body>
</html>
Mj Jam
  • 173
  • 4
  • 6
  • 16
  • 1
    Always check server side as well. Even if JavaScript validation is used, it is trivially easy to bypass that. On the server side send an error if there user-name is already in use. Never just rely on data from the client as being validated already. – Anigel Jul 28 '13 at 16:13
  • Also, please use our search feature. See [how to disable submit button with jquery](http://stackoverflow.com/q/1237896/911182) – Herbert Jul 28 '13 at 16:16

1 Answers1

1

You'll wanna use .attr('disabled', 'disabled') on the the element you want to disable, if the check returns that the username already exists. And to remove the disabling you'll use .removeAttr('disabled').

And just a recommendation, if you havn't already throw in a fallback php validation check that way if javascript is disabled there is still validation in place.

BrotherBallan
  • 369
  • 2
  • 6