I have a function to validate a code with AJAX(PHP). However, when I try to run it, it returns undefined
when it should return true
or false
.
function:
function verifyViite(viite) {
$.get('dataminer.php?question=validateViite&q='+viite, function(data) {
jQuery.globalEval(data);
if(valid == 1) {
return true;
}
else {
return false;
}
});
}
The data
is either valid = 1;
or valid = 0;
I have a function to validate a code with AJAX(PHP). However, when I try to run it, it returns undefined
when it should return true
or false
.
function:
function verifyViite(viite) {
$.get('dataminer.php?question=validateViite&q='+viite, function(data) {
jQuery.globalEval(data);
if(valid == 1) {
return true;
}
else {
return false;
}
});
}
The data
is either valid = 1;
or valid = 0;
2 Answers
Reset to default 5You can't return the Callback return value due to the AJAX request being asynchronous.
Execute whatever code calling verifyViite
inside the callback itself, instead of returning true or false.
Alternativly, you can have synchronous AJAX request.
since the function veryViite doesn't return anything, undefined is the expected result. Since its asynchronouse, you would have to give a callback function that would be called on successful ajax call. Something like this;
function verifyViite(viite,cb) {
$.get('dataminer.php?question=validateViite&q='+viite, function(data) {
jQuery.globalEval(data);
if(valid == 1) {
cb(true);
}
else {
cb(false);
}
});
}
and the call would be like;
verifyViite(viite,function(good){
alert(good);
});