admin管理员组

文章数量:1309963

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;

Share Improve this question edited Oct 9, 2011 at 12:36 Axel Latvala asked Oct 9, 2011 at 12:07 Axel LatvalaAxel Latvala 5763 gold badges8 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You 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);
});

本文标签: javascriptajax function returning undefinedStack Overflow