views:

28

answers:

1

Hi Guys/Gals

I have the following function:

function validateField(query) {
    new Request.JSON({
        onRequest  :  function() {

        },
        onSuccess : function(json){
            return true;
        },      
        data : query + '&validate=true',
        url  : base + 'ninjquiry.php'
    }).send();              
}

Now onSuccess is definitely firing because I can put a console.log in there and it works, however if I do the following somewhere else:

console.log(validateField(query));

I get "undefined". Why is this ?

Thanks for any help in advance

  • Alex
+1  A: 

Ajax is asynchronous. The onSuccess callback is called later, after the validateField function has been finished. The return true will vanish into thin air.

You would have to either make your call synchronous - I'm sure MooTools has a setting for it - but that is highly discouraged, as it can freeze the browser.

Or, this is the better alternative, change your code so that everything relevant happens in the onSuccess callback.

Pekka
I needed to perform some actions on an element but I suppose you're right and I can pass that element through as an argument. Thank you for the answer.
beingalex
@beingalex you're welcome. Passing the element through shouldn't be a problem, a variable you use in (or pass to) the `validateField` function will be automatically available in the `onSuccess` callback.
Pekka