0

I have created a JavaScript object and I am trying to do a jQuery AJAX request and set a variable in the object based on the response, but it's not working. The variable returns empty. Here's the code...

$(document).ready(function() {

var DoStuff = {

    clientToken : null,
    userToken: null,

    init : function() {
        this.getUserToken();
    },

    setClientToken : function(token) {
        this.clientToken = token;
        this.init();
    },

    getUserToken : function() {


        $this = this;

        var request = $.ajax({
          url: "/api/user/current_user/",
          type: "POST",
          data: { clientToken : this.clientToken },
          dataType: "json"
        });

        request.done(function(response) {
            if(response.userToken) {
                /* this should be setting the DoStuff.userToken variable */
                $this.userToken = response.userToken;
            }else {
                $this.userToken = "didn't work :(";
            }       
        });

    }, 

    setUserToken : function(token) {
        this.userToken = token;
    },

    showUserToken : function() {

        alert(this.userToken);

    }

};

//-> Set the client all requests will be sent on behalf of
DoStuff.setClientToken("clienttokenherewooo");
DoStuff.showUserToken(); // this should show the value the AJAX returned, but it's empty
});
Ben
  • 21
  • 2
  • you need to return the object you passed – abc123 Sep 19 '13 at 18:42
  • 1
    Maybe your AJAX request isn't complete by the time you hit showUserToken(). What happens when you try to run that line at a later point in time? – Michael Sep 19 '13 at 18:45
  • Remember, AJAX is *asynchronous*! JavaScript does **not** wait for the call to be done before continuing. It moves on letting the AJAX go in the background. When you call `showUserToken`, the call isn't done yet, the token wasn't downloaded yet. You need to use callbacks for this. You need to call `DoStuff.showUserToken();` in the `request.done` function. – gen_Eric Sep 19 '13 at 18:47

1 Answers1

2

AJAX is asynchronous. In function getUserToken return the ajax object and do something like that:

DoStuff.getUserToken().done(function(result) {
    // blablabla
}).fail(function(result) {
    // error blablabla
});
ias
  • 76
  • 3