1

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.

pavon147
  • 11
  • 1

2 Answers2

2

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!

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Whoa, that answer wasn't there when I started mine. I didn't get the notification. Sorry for the identical answer - quite right that you get the upvotes for being the early bird. – Mitya Nov 25 '14 at 12:23
  • 1
    @Utkanos - No problem, happens to me all the time as well. – adeneo Nov 25 '14 at 12:23
0

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); });
Mitya
  • 33,629
  • 9
  • 60
  • 107