-2

Is it possible to call a function in success callback of ajax request?

For example I have something like that :

constructor(private http: HttpClient,private serviceComposition: CompositionService) { }

[...]

save() {

    var isValid = this.isValidCompo();

    if (true) {
        var toSend = JSON.stringify(this.setupComposition);
        $.ajax({
            url: "/api/setup/composition/addSetupComposition",
            type: 'POST',
            dataType: "json",
            data: 'setupComposition=' + toSend,
            success:function(response){
                //console.log("Success Save Composition");

            },
            error: function(XMLHttpRequest,textStatus,errorThrown){
                console.log("Error Save Compo");
            }
        }).done(function(data){
            this.serviceComposition.changeValue(isValid);
        })
    } 
}

I want to call a function of my service (named : changeValue() ) if my ajax request is a success.

But I have this error message : core.js:12632 ERROR TypeError: Cannot read property 'changeValue' of undefined

Do you know if it's possible to resolve that ?

Mathieu d.o
  • 113
  • 5
  • Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Kevin B Mar 05 '19 at 20:34

2 Answers2

1

I am suspecting this binding is going wrong in call backs, prefer using arrow function because of "this" operator binding.

 if (true) {
    var toSend = JSON.stringify(this.setupComposition);
    $.ajax({
        url: "/api/setup/composition/addSetupComposition",
        type: 'POST',
        dataType: "json",
        data: 'setupComposition=' + toSend,
        success:function(response){
            //console.log("Success Save Composition");

        },
        error: function(XMLHttpRequest,textStatus,errorThrown){
            console.log("Error Save Compo");
        }
    }).done((data) => {
        this.serviceComposition.changeValue(isValid);
    })
}

if not u can store this reference in a variable and call it

 var self = this;
 if (true) {
    var toSend = JSON.stringify(this.setupComposition);
    $.ajax({
        url: "/api/setup/composition/addSetupComposition",
        type: 'POST',
        dataType: "json",
        data: 'setupComposition=' + toSend,
        success:function(response){
            //console.log("Success Save Composition");

        },
        error: function(XMLHttpRequest,textStatus,errorThrown){
            console.log("Error Save Compo");
        }
    }).done(function(data){
        self.serviceComposition.changeValue(isValid);
    })
}
anees
  • 336
  • 1
  • 6
  • Thanks a lot both method work well ! Do you know if it's possible to call get ajax function in the success of my POST request ? to replace isValid by a result of a get request – Mathieu d.o Feb 28 '19 at 17:33
0

Use an arrow function to access this of your parent scope. In your example, this is referring to your jQuery XHR object.

So:

// [parent scope]

$.ajax({
  ...
}).done((data) => {
  // [child scope]
  // `this` now refers to [parent scope], so the following is valid
  this.serviceComposition.changeValue(isValid);
});

Another common practice prior to arrow functions (ES6) would've been assigning a const self = this; variable in the [parent scope] area to be accessed in the child method. Either method works the same.

Also check out the MDN docs on this. It's a confusing topic for many.

Sheng Slogar
  • 1,162
  • 7
  • 15