geeky_monster
geeky_monster

Reputation: 8792

How to tackle asynchronous nature of javascript?

I have a simple HTML form . I am trying to do a series of validations for the form using javascript .

$("#sign_in_form").submit(function(event){
    event.preventDefault();
    if(check_validity()){
        console.log("valid");
        return true;
    } else {
        console.log("invalid");
        return false;
    }

    console.log("end of function");    
});

Now check_validity() is a time consuming function . It checks data from the database and then replies with true or false. But the above function doesn't seem to wait for check_validity to complete and runs the else statement, before the check validity is complete.

How do I fix this? Probably using a callback function can fix this. But how do I receive a return value using callback?

function check_validity(){
    $.post("http://xxxx.com/check_if_user_exists",
    {email: $("#contact_person_email").val()},
    function(data){
        if(parseInt(data) == 1)
            return false;
        else
            return true;
    });
} 

Upvotes: 0

Views: 158

Answers (1)

zerkms
zerkms

Reputation: 254924

Use jquery deferred:

function check_validity(){
    return $.post("http://xxxx.com/check_if_user_exists", {
        email : $("#contact_person_email").val()
    }).then(function(data) {
        return parseInt(data, 10) != 1;
    });  // end of post 
} //end function 

Usage:

check_validity().done(function(valid) {
    if (valid) {
        // ...
    }
});

But you still won't be able to use it to decide on whether to return true or false in submit(). It's just impossible for async calls.

Upvotes: 1

Related Questions