Reputation: 241
I'm trying to do a ajax check of username availability and submitting a form only if the username is available.
Using jQuery Validation plugin, I have set:
submitHandler: function(form) {
if (ajaxCheck() == true){
alert('true');
}
}
And my username checking function looks like this:
function ajaxCheck(){
usernameVal = $("#username").val().toLowerCase();
usernameVal = usernameVal.replace(/[\s\W]/g, '');
$.post("/app/signup/username/", {
username: usernameVal
}, function(response){
if (response == "Username not available.") {
$("#signup").validate().showErrors({ "username" : "Username Not Available." });
alert('false');
return false;
} else {
alert('true');
return true;
}
});
}
The problem is it's not returning true or false to the submitHandler. I'm not sure if it's because the return statements are within the $.post ?
If I run the ajaxCheck independently, it does alert false and true based on availability, it's just not returning false/true if it's called from submitHandler.
Any insights appreciated.
Upvotes: 1
Views: 3088
Reputation: 21
you can use remote option too, like this!
remote: {
url: myUrl = location.protocol + "//" + location.host + '/trabajos/json.php?c=wrk&a=validMail',
type: "post",
data: {
correo: function() {
return $("#subtrabajo_correo").val();
}
}
}
Upvotes: 2
Reputation: 241
Awesome, working now with:
$.validator.addMethod("usercheck", function(value, element) {
ajaxCheck();
return validName;
}, "Username not available!");
and setting a variable "validName" instead of returning true/false in ajaxCheck();
Upvotes: -1
Reputation: 15835
Novon ,
You can set a variable inside a success of ajax, but to my knowledge you cannot return a value from the ajax.
its a asyncronous call , so maintain a global variable move your logic of checking to the succuess.
You can not make a ajax call and get return value like a method
Upvotes: 0