The following is a little jQuery code that I wrote to check if a a username and email exists in database. If they do I return false to prevent submitting the form.
The way I planned it is something like this.
On submit after other stuff is valid. I use an ajax request to check if the username exists. If It does I then check the email in the same way.
And here is the problem. I cannot set the everythingIsOK inside the ajax callback. So if everything is ok I cannot return true.
Any ideas?
$(loginForm).submit(function(){
var = everythingIsOK = false;
if((loginForm).valid()){
$.get("/ajax/usernameAvailable", {username: $("#username").val()}, function(data){
if(data.available){
$.get("/ajax/emailAvailable", {email: $("#email").val()}, function(data){
if(data.available){
everythingIsOK = true;
return true;
}else{
$("#notAvailable").html("Email already exists.").show().fadeOut(8000);
return false;
}
}, "json");
}else{
$("#notAvailable").html("This is username already exist.").show().fadeOut(8000);
}
}, "json");
}
return everythingIsOK;
});
You can call the native
form.submit()function (which won’t trigger this handler again) if it is ok, and returnfalsefrom the jQuery handler always, like this:When the check finishes (comes back from the server), you’ll either get an error, or the form will submit and move on. Also I changed
$(loginFormabove to not be wrapped again, judging byif((loginForm).valid()){(if that isn’t erroring), it’s already a jQuery object.