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}
thisdoes not refer tocellule
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With