I want to validate a form such that I can check the basics (such as username entered, username a minimum length, etc.) but also such that I can ensure things like username and email have not already been (which requires a database search).
I have all the pieces, and after playing around have narrowed it down to find that the $.post statement, while it is meant to add to my ‘fail’ counter, is not doing so. How can I get some form of output from the $.post line so that I can truly validate (because right now, even if the username is not available, it will submit the form).
Here is my <script> (although for simplicity shortened to just show the username piece). Note that ‘usernameoff’ is my error block:
function validateForm()
{
// set variables
var username=document.forms["registrationnew"]["username"].value;
var usernamespace=username.indexOf(" ");
// set fail counter variable to determine if any requirements failed
var counter=0;
// check that username isn't blank, containing spaces, too short, or taken
if (username==null || username=="")
{
counter++;
$('#usernameoff').html("Must enter a username");
}
else if (username.indexOf(" ") >= 0)
{
counter++;
$('#usernameoff').html("Cannot contain spaces");
}
else if (username.length < 3)
{
counter++;
$('#usernameoff').html("Must be at least three characters");
}
else
{
$.post("check_username.php", {username: username}, function(result)
{
if(result == 0)
{
$('#usernameoff').html("Available");
}
else
{
counter++;
$('#usernameoff').html("Not available");
}
});
}
// if any test failed, return false
if (counter > 0)
{
document.getElementById("errorflag").innerHTML=counter;
return false;
}
}
$.post conducts a query to determine whether or not the username entered has already been taken (and returns 0 or 1). My issue is that, regardless of which it returns, it does not increment ‘counter’, and therefore the form still submits.
Your final test (
if (counter > 0)) will run before your AJAX call has returned. This is the ‘asynchronous’ part of AJAX.The simplest solution, in your case, is to replace
$.postwith a synchronous call:This will cause a delay while your script waits for the return, but since it’s on your own server, that delay should be fairly minimal.
(Synchronous calls aren’t always possible. Read the docs for
.ajax()for more.)