I am trying to validate a html form using jquery,ajax and php. I've written this function in jquery that checks for the availability of a username using ajax post request.However, the problem is that it is always returning a false. I'm new to jquery and javascript. I've tried quite a bit but I'm unable to figure out the problem. Please help.
function isvalid_username()
{
var username=$('#username').val();
var option=false;
if(username == "")
{
$('#username').removeClass('valid').addClass('invalid');
$('#username_feedback').addClass('error').html("Please choose a username!!");
option=false;
}
else if(username.length < 4)
{
$('#username').removeClass('valid').addClass('invalid');
$('#username_feedback').addClass('error').html("Your username must be atleast 4 characters.");
option=false;
}
else
{
$.post('php/check_username_avail.php',{ username : username },function(data){
if(data == "false")
{
$('#username').removeClass('valid').addClass('invalid');
$('#username_feedback').addClass('error').html("Sorry! That username is already taken. Try a different one.");
option= false;
}
else if(data == "true")
{
$('#username').removeClass('invalid').addClass('valid');
$('#username_feedback').html("");
alert('Now it should return true');
option=true;
}
else
{
$('#username').removeClass('valid').addClass('invalid');
$('#username_feedback').addClass('error').html(data);
option=false;
}
}).error(function(){
alert("An error occurred. Unable to validate username");
});
}
return option;
}
EDIT: I've read the other post. But I still don't find a way to validate the form. I want to use this submit handler function with my code:
$('#signup_form').submit(function(event)
{
if(isvalid_first_name() && isvalid_username() && isvalid_email() && isvalid_password())
{
alert('Submitting the form');
}
else
{
event.preventDefault();
$('#submit_feedback').html("Please correct the above problems first");
}
});
If it can't be done this way, then what other technique should I use to validate the form on clientside?