user1422442
user1422442

Reputation: 66

Jquery $.ajax Get response conflicting with nested passing of 'this' object to 'success' callback function

I am trying to do a jquery $.ajax Get inside a method of a class. The data supplied by the Get request to be used in the callback function on success and also the class needs to be modified inside the same callback. So, I had to .apply the callback on the this identifier of the original class since otherwise ,inside the callback, this was getting replaced locally. But while applying callback to this the data returned by Get is coming as undefined. How do I work around this problem. Any help appreciated.

var tableblock = function(tablename){
     this.tablename = tablename;
     this.numusers = 0;
     this.userpool = new Array();

     this.addme = function(){
        bodyContent = $.ajax({
            type: "GET",
            url: "controllers/bestpals.php",
            data: "addpal=1&palname="+userid+"&nocache="+Math.floor((Math.random()*100)+1),
            error: function(xhr, statusText){alert('could not add pal. refresh page.');},
            success: function(msg){
                alert(msg); // this will give undefined when .apply(this) 
                myid = msg;
                syncpals(this,true);
            }.apply(this) // using this alert(msg) above gives undefined 
        });
     };
 }

Upvotes: 0

Views: 601

Answers (3)

bobince
bobince

Reputation: 536597

I think you meant bind not apply. bind creates a new function that calls the wrapped one whilst setting this; apply calls the function straight away as soon as addme() runs.

However bind is an ECMAScript Fifth Edition feature, so you'd need to do one of:

  1. polyfill bind for older browsers;
  2. use the jQuery equivalent proxy;
  3. use the context argument to ajax, which sets this explicitly;
  4. remember var that= this; in addme and use the enclosed that reference in the inner function.

Upvotes: 1

Eric
Eric

Reputation: 97641

You want .bind(this), not .apply(this). bind changes the this pointer of a function, while apply actually runs the function in the new context.

Upvotes: 1

lanzz
lanzz

Reputation: 43178

You can provide a context parameter in your ajax configuration; all ajax callbacks will be called in that context (i.e., this inside the callback will refer to the value you pass as context in your $.ajax() call):

SomeClass.prototype.methodName = function() {
    $.ajax({
        ....
        context: this    // callbacks will be called with the same context that methodName() is running in
        ....
    });
}

Upvotes: 5

Related Questions