3

Sorry for the duplication but I can find any solution in the others posts.

I'm trying to fill a javascript object using a ajax call to a webservice. I don't understand the logic of this and why my object in not set after the call. I wrote this little example to explain my problem :

Code :

function Cellule(){
    this.test = 0;
    this.textfunction();
}

Cellule.prototype.textfunction = function(){
    this.test = 1;
    $.ajax({
        type: "GET",
        url: "BASEURL/cellules", 
        data: "",
        success: function(msg){
            console.log("success");
            this.test = 2;
            console.log(cellule);
        }
    });
};

var cellule = new Cellule();

Console out :

success
Cellule {test: 1}
Gauthier
  • 1,116
  • 2
  • 16
  • 39

3 Answers3

9

this does not refer to cellule

Use .bind() or context in argument of ajax settings

The bind() method creates a new function that, when called, has its this keyword set to the provided value

Or specifying context: this will use context of cellule in success handler.

Try this:

function Cellule() {
  this.test = 0;
  this.textfunction();
}

Cellule.prototype.textfunction = function() {
  this.test = 1;
  $.ajax({
    type: "GET",
    url: "../slimrest/andon/cellules",
    data: "",
    success: function(msg) {
      console.log("success");
      this.test = 2;
      console.log(cellule);
    }.bind(this)
  });
};

var cellule = new Cellule();
Rayon
  • 36,219
  • 4
  • 49
  • 76
  • Well done . Work perfectly – Gauthier Mar 11 '16 at 12:44
  • Happy to help! Kindly [accept and up-vote](http://meta.stackexchange.com/questions/23138/how-to-accept-the-answer-on-stack-overflow) the best solution which has solved the purpose :) __Happy coding!__ – Rayon Mar 11 '16 at 12:45
1

Your issue gets caused because of the fact that the this-scope changed when using the ajax call.

Binding the this scope to the call should solve your issue.

function Cellule(){
    this.test = 0;
    this.textfunction();
}

Cellule.prototype.textfunction = function(){
    this.test = 1;
    $.ajax({
        type: "GET",
        url: "../slimrest/andon/cellules", 
        data: "",
        success: function(msg){
            console.log("success");
            this.test = 2;
            console.log(cellule);
        }.bind(this)
    };
};

var cellule = new Cellule();
Matthijs
  • 3,162
  • 4
  • 25
  • 46
1

Your this in your AJAX success handles refers to the AJAX call, not to your object. Try this:

Cellule.prototype.textfunction = function(){
    this.test = 1;
    var _this = this;
    $.ajax({
        type: "GET",
        url: "BASEURL/cellules", 
        data: "",
        success: function(msg){
            console.log("success");
            _this.test = 2;
            console.log(cellule);
        }
    });
};
Roboroads
  • 1,602
  • 1
  • 13
  • 24