Skip to content Skip to sidebar Skip to footer

Javascript Class Property Not Set In Success Function Of Ajax Call

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

Solution 1:

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:

functionCellule() {
  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 = newCellule();

Solution 2:

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.

functionCellule(){
    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 = newCellule();

Solution 3:

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

Post a Comment for "Javascript Class Property Not Set In Success Function Of Ajax Call"