简体   繁体   中英

Use javascript variable outside success function

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");

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 accomplish this by setting async: false .

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

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

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

http://net.tutsplus.com/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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM