Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript class property not set in success function of ajax call [duplicate]

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}
like image 946
Gauthier Avatar asked Dec 06 '25 10:12

Gauthier


2 Answers

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();
like image 149
Rayon Avatar answered Dec 08 '25 00:12

Rayon


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();
like image 43
Matthijs Avatar answered Dec 08 '25 00:12

Matthijs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!