最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ajax function returning undefined - Stack Overflow

programmeradmin0浏览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;

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);
});
发布评论

评论列表(0)

  1. 暂无评论