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

jquery - Use javascript variable outside success function - Stack Overflow

programmeradmin2浏览0评论

I have used jquery validation to validate email. But the variable whose value is changed in success function is not accessible outside it. It can be done with async=false, but that destroys the purpose of Ajax.

Below is the code:

$.validator.addMethod('verifyemail',function(value,element){        
    $.ajax({
        type: "POST",
        url : $.app.urls('base_url')+'account/check_email',
        data: {'email' : value},
        success: function(msg){
            //If email exists, set response to true
            if( msg.status == 'false' )
                respond = false;
            else
                respond = true;
        }
    })
    console.log(respond);
    return respond;
}, "Email is Already Taken");

I have used jquery validation to validate email. But the variable whose value is changed in success function is not accessible outside it. It can be done with async=false, but that destroys the purpose of Ajax.

Below is the code:

$.validator.addMethod('verifyemail',function(value,element){        
    $.ajax({
        type: "POST",
        url : $.app.urls('base_url')+'account/check_email',
        data: {'email' : value},
        success: function(msg){
            //If email exists, set response to true
            if( msg.status == 'false' )
                respond = false;
            else
                respond = true;
        }
    })
    console.log(respond);
    return respond;
}, "Email is Already Taken");
Share Improve this question asked Jul 17, 2013 at 5:06 Tiny JaguarTiny Jaguar 4333 gold badges14 silver badges30 bronze badges 1
  • Problem: Trying to use undefined variable. Explanation: AJAX request will take some time, you can't read results right after $.ajax call. Solution: Event driven program flow, separate validator methods and AJAX requests. Check for valid and default to invalid. – Sampo Sarrala Commented Sep 28, 2013 at 19:25
Add a ment  | 

4 Answers 4

Reset to default 4

You can't set the value in an asynchronous function like that. The way in which this works is that respond would be set to a value. Then your asynchronous ajax call would fire off, as soon as it fires off the rest of the code below your ajax call would execute. Once the ajax call returns, the code in the success callback will be executed. Most likely, by this time your validator function would have finished executing.

Since you're using this ajax call in a validator, you would want to run this in series since the validation depends on the result of your ajax call. You could acplish this by setting async: false.

Here is a useful resource on asynchronous callbacks and how they work:

http://blog.parse./2013/01/29/whats-so-great-about-javascript-promises/

And another covering jQuery's AJAX function async vs sync:

http://net.tutsplus./tutorials/javascript-ajax/event-based-programming-what-async-has-over-sync/

Ajax call is asynchronous, meaning when you call console.log(respond); The variable respond is still not available. If you need to access it outside the success function, you can trigger a custom event and get respond in the event handler.

And of course, you have to put respond in outer scope.

respond is already a global variable (lack of var keyword), but the asynchronous nature of AJAX means that it won't necessarily be available when the following lines run, so you need to sequence it in one of a few ways

  • Make it synchronous (but the question rules that out)
  • put the responding code inside of the same anonymous function
  • You could also make a while loop that spins until respond is set, but that would probably be a poor solution.

Hope that helped

to access the respond variable you need to either define it in upper scope

$.validator.addMethod('verifyemail',function(value,element){        
    var respond = true; // scope of variable to current function
    $.ajax({
        type: "POST",
        url : $.app.urls('base_url')+'account/check_email',
        async: false,  
        data: {'email' : value},
        success: function(msg){
            //If email exists, set response to true
            if( msg.status == 'false' )
                respond = false;
            else
                respond = true;
        }
    })
    console.log(respond);
    return respond;
}, "Email is Already Taken");
发布评论

评论列表(0)

  1. 暂无评论