Question

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)
    });
};
Was it helpful?

Solution

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
        });
    });
};

OTHER TIPS

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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top