user240880
user240880

Reputation: 13

Retrieving response while preserving scope of "this" with jquery ajax

I used a closure to set this to _this inside the ajax success but now I have of course lost "response". Anybody know a way to retrieve the response data in this instance?

var form = {       
    name: 'great form',    
    load:function() {
        $.ajax({
        url: "get/data",
        type: "POST",
        success: function(_this){
                console.log(_this.name);     // outputs : "great form"
                console.log(response.data);  // response is undefined
        }(this)
    });
};

Upvotes: 1

Views: 318

Answers (2)

jfriend00
jfriend00

Reputation: 707786

You don't want to change the argument to your success handler. That first argument to the success handler is your ajax response data so you need to treat it as such.

To get access to the this pointer in your success handler, there are several methods. The one I think is the most elegant is that jQuery allows you to pass in the context that you want this to be set to in your success callback as one of the arguments to the $.ajax() function as shown here:

var form = {       
    name: 'great form',    
    load:function() {
        $.ajax({
        context: this,      // sets 'this' pointer for success callback
        url: "get/data",
        type: "POST",
        success: function(response){
                console.log(this.name);      // outputs : "great form"
                console.log(response.data);  // ajax response data
        });
    });
};

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075139

You don't want _this as an argument on the success function (and the way you were doing it was calling the function immediately, not waiting for jQuery to call it on success), you create it as a variable alongside the ajax call:

var form = {       
    name: 'great form',    
    load:function() {
        var _this = this; // <=== Here
        $.ajax({
        url: "get/data",
        type: "POST",
        success: function(response){
                console.log(_this.name);     // outputs : "great form"
                console.log(response.data);  // response is undefined
        }
    });
};

Of course, with that code, you could just use form.name, since it's a one-off object.

More:

Upvotes: 1

Related Questions