Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function returns undefined on firebug [duplicate]

Possible Duplicate:
How to return the response from an AJAX call from a function?

on my App namespace i've just defined a function:

version 1

window.App = {
  isLogged: function () {
    $.get('/user/isLogged', function (data) {
      if (data == 'true') {
        return true;
      }
      return false;
    });
  }
};

version 2

window.App = {
  isLogged: function () {
    var test = $.get('/user/isLogged');
    console.log(test.responseText);
  }
};

On version 1 when i try the function on firebug 'App.isLogged()' i got a nice undefined :S

On version 2 when i try the function on firebug, the responseText seems to be undefined :stuck:

I'm pretty new about javascript, and maybe a scope issue...

The goal of my function is clear i think, there's a better way to achieve this?

like image 558
cl0udw4lk3r Avatar asked Sep 17 '26 11:09

cl0udw4lk3r


1 Answers

on first version $.get is asynchronous that's why you don't get a return value

on second version $.get returns deferred object that doesn't have responseText field

window.App = {
  isLogged: function () {
    var dfd = $.Deferred();
    $.get('/user/isLogged', function (data) {
      if (data == 'true') {
        return dfd.resolve();
      }
      return dfd.reject();
    });
    return dfd.promise();
  }
};

$.when(App.isLogged()).then(function() {
  //your code
}).fail(function() {
  //fail code
});
like image 120
salexch Avatar answered Sep 19 '26 02:09

salexch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!