2

Possible Duplicate:
$(this) inside of AJAX success not working

I have the following sample code (JSFiddle to follow)

AdvancedSearch = function() {
    this.current = 'test';
}

AdvancedSearch.prototype.InitPage = function() {
    var t = this.current;
    this.PrePopulate()

}

AdvancedSearch.prototype.UpdateData= function() {
    alert(this.current);
}

AdvancedSearch.prototype.PrePopulate = function() {
    this.UpdateData();

    $.ajax({
        url: 'http://fiddle.jshell.net/',
        success: function(msg) {
            this.UpdateData();
        }
    });
}

var as = new AdvancedSearch();
as.InitPage();​

I have the 'http://fiddle.jshell.net' in there so prevent the Access-Control-Allow-Origin error on their site.

When executing this code, I get the following error:

Uncaught TypeError: Object # has not method 'UpdateData'

If you execute the JSFiddle, you will find that when PrePopulate is called, it runs the this.UpdateData() at the beginning of the function just fine. But as soon as the Ajax call is finished, you get the error.

Any thoughts to why this is happening? Perhaps I'm approaching this in the wrong way. Any insight would help.

Here is my JSFiddle: http://jsfiddle.net/B4NRY/2/

Community
  • 1
  • 1
CodeLikeBeaker
  • 20,682
  • 14
  • 79
  • 108
  • The `this` when the success callback function is called isn't the same `this` as your object. dystroy below has the solution to this very common JavaScript problem. – Matt Burland Oct 08 '12 at 17:27

1 Answers1

8

The callback you give to $.ajax isn't called with your instance of AdvancedSearch as context (this).

Solution 1 (valid for all the similar callback problems ) :

AdvancedSearch.prototype.PrePopulate = function() {
    this.UpdateData();
    var that = this; // register the that variable in the closure of the callback
    $.ajax({
        url: 'http://fiddle.jshell.net/',
        success: function(msg) {
            that.UpdateData();
        }
    });
}

Solution 2 (specific to $.ajax but very clean, thanks Felix) :

AdvancedSearch.prototype.PrePopulate = function() {
    this.UpdateData();
    $.ajax({
        url: 'http://fiddle.jshell.net/',
        context: this,
        success: function(msg) {
            this.UpdateData();
        }
    });
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758