tags:

views:

9

answers:

0

I am using motools - formcheck to validate my input. When submit is pressed I want the validation of the input to send an ajax request so I added validate['required','%checkIfUsernameExists']

I have a feeling since JSON request is most likely asynchronous by the time the response is processed, el is now an undeclared variable. How can I get this working?

WORKS
    function doesUsernameExist(el){    
                        el.errors.push("Username is taken");
                        return false;

            new Request.JSON({
                url: "/index.php/script/check_username/" + el, 
                onSuccess: function(response){     
                    if(response.action == 'success'){ 
                        el.errors.push("Username is free");
                        return true;                                                
                    }else{                     
                        el.errors.push("Username is taken");
                        return false;
                    }

                }
            }).get($('signup'));
        });  
    }


DOES NOT WORK
    function doesUsernameExist(el){    
            new Request.JSON({
                url: "/index.php/script/check_username/" + el, 
                onSuccess: function(response){     
                    if(response.action == 'success'){ 
                        el.errors.push("Username is free");
                        return true;                                                
                    }else{                     
                        el.errors.push("Username is taken");
                        return false;
                    }

                }
            }).get($('signup'));
        });  
    }