Reputation: 473
Why the return value of my function always false
this is my function:
function checkUsername(username) {
var ret=false;
$.ajax({
type: "POST",
url: "user_validate.php",
async: true,
data: "username="+username,
success: function(data){
if(data == 0){
ret = true;
}else{
ret = false;
}
},
error:function() {
alert("ERROR");
}
});
return ret;
}
Is var ret doesn't set the value? Anything wrong with it..? thanks before..!
Upvotes: 0
Views: 361
Reputation: 8210
You're a little confused on the scope of things here. The ajax call is asynchronous, so by the time it answers, it no longer has anything to do with the function it was called from. What you really want to do is either set up some sort of event listener or a (my preferred method) callback.
Also, do yourself a favor and use the shortened syntax $.post(): http://api.jquery.com/jQuery.post/
function checkUsername(username) {
$.post("user_validate.php", "username=" + username, function(data) {
if (data == 0) {
// Update DOM or element, or whatever you want to do
} else {
// Handle negative result
}
});
}
Upvotes: 0
Reputation: 700562
Because the AJAX call is asynchronpous, so you return the value of ret
before it's assigned.
Use a callback method to handle the result:
function checkUsername(username, callback) {
var ret=false;
$.ajax({
type: "POST",
url: "user_validate.php",
async: true,
data: "username="+username,
success: function(data){
callback(data == 0);
},
error:function() {
alert("ERROR");
}
});
}
Usage:
checkUsername(username, function(success){
if (success) {
alert('User name is valid.');
} else {
alert('User name is not valid.');
}
});
Upvotes: 0