I am very new to jQuery and javascript programming. I have a program below that checks whether username is taken or not. For now, the PHP script always returns
if(isset($_POST["username"]) )//&& isset($_POST["checking"]))
{
$xml="<register><message>Available</message></register>";
echo $xml;
}
Login function works, but username checking doesn’t. Any ideas?
Here is all of my code:
$(document).ready(function() {
jQuery.validator.addMethod("checkAvailability",function(value,element){
$.post( "login.php" , {username:"test", checking:"yes"}, function(xml){
if($("message", xml).text() == "Available") return true;
else return false;
});
},"Sorry, this user name is not available");
$("#loginForm").validate({
rules: {
username: {
required: true,
minlength: 4,
checkAvailability: true
},
password:{
required: true,
minlength: 5
}
},
messages: {
username:{
required: "You need to enter a username." ,
minlength: jQuery.format("Your username should be at least {0} characters long.")
}
},
highlight: function(element, errorClass) {
$(element).fadeOut("fast",function() {
$(element).fadeIn("slow");
})
},
success: function(x){
x.text("OK!")
},
submitHandler: function(form){send()}
});
function send(){
$("#message").hide("fast");
$.post( "login.php" , {username:$("#username").val(), password:$("#password").val()}, function(xml){
$("#message").html( $("message", xml).text() );
if($("message", xml).text() == "You are successfully logged in.")
{
$("#message").css({ "color": "green" });
$("#message").fadeIn("slow", function(){location.reload(true);});
}
else
{
$("#message").css({ "color": "red" });
$("#message").fadeIn("slow");
}
});
}
$("#newUser").click(function(){
return false;
});
});
You need to use the expanded form of
$.post()which is$.ajax()so you can set theasyncoption to false, like this:Currently your
successfunction that analyzes the response happens after the validation finishes, because it’s an asynchronous operation. So currently, it’s not returning anything at the time the return value is used, andundefined~=false, which is why it always appears false. By settingasynctofalse, you’re letting the code execute in order without the callback, so the return in the example above is actually used.Another alternative, if you can adjust your page’s return structure is to use the validation plugin’s built-in
remoteoption, which is for just this sort of thing 🙂