pavon147
pavon147

Reputation: 11

Wait for return from function

I've got that piece of code:

var result;

$.when(result=make_req("GET", "ajax.php?request=opendiv", true, null, null)).done(alert(result));

Can you tell me, why does alert show 'undefined'?

make_req() makes some ajax call, it works properly and returns good value when I call it alone.

I want to store results from make_req in the variable 'result' and then use it.

Upvotes: 1

Views: 104

Answers (2)

Mitya
Mitya

Reputation: 34556

Because done() expects a callback function to be passed as its only parameter, whereas you are passing the return value of alert. You need:

.done(function(result) { alert(result); });

Upvotes: 0

adeneo
adeneo

Reputation: 318182

You're executing the alert right away, you're not waiting for the result

You have to reference a function, not call it, and adding the parenthesis to a function will call it, in this case you can use an anonymous function instead, and call alert inside that

$.when( make_req("GET", "ajax.php?request=opendiv", true, null, null) )
   .done(function(result) {
        alert(result);
});

Of course, make_req() has to return a deferred promise!

Upvotes: 2

Related Questions