0

how to call another method inside jquery ajax?

methods : {
    calert(type,msg="",error=""){
        console.log("call me");
    },
    getData(){
        $.ajax({
            type: "GET",
            success: function(data){
                // error calert not found
                calert(true,"","asd");
            },
            error: function (error) {
                // also error calert not found
                this.calert(false,"",error);
            },
            complete: function(){
            },
            url: "/test",
        });
    },
}

i have try to using this.calert but it doesn't work, still error

2 Answers 2

1

You simply need to update your code to use arrow functions, as follows:

methods : {
    calert(type,msg="",error=""){
        console.log("call me");
    },
    getData(){
        $.ajax({
            type: "GET",
            success: (data) => {
                this.calert(true,"","asd");
            },
            error: (error) => {
                this.calert(false,"",error);
            },
            complete: (){
            },
            url: "/test",
        });
    },
}

Or alternatively, store a local reference to the method, like:

methods : {
    calert(type,msg="",error=""){
        console.log("call me");
    },
    getData(){
        const { calert } = this;

        $.ajax({
            type: "GET",
            success: function(data){
                // error calert not found
                calert(true,"","asd");
            },
            error: function (error) {
                // also error calert not found
                calert(false,"",error);
            },
            complete: function(){
            },
            url: "/test",
        });
    },
}
0
0

btw i found the solution, looks like little bit tricky using this

methods : {
    calert(type,msg="",error=""){
        console.log("call me");
    },
    getData(){
        let vm = this;
        $.ajax({
            type: "GET",
            success: function(data){
                // error calert not found
                vm.calert(true,"","asd");
            },
            error: function (error) {
                // also error calert not found
                vm.calert(false,"",error);
            },
            complete: function(){
            },
            url: "/test",
        });
    },
}

i store the this to variable and then i use the variable to call another methods.

Anyone have any solutions better than this?

Thanks

1
  • assigning this to variable has been made obsolete with the introduction of arrow functions, which have access to global context. just use them in ajax callbacks. for ex: success: (data) => this.calert(true, "", "asd") Commented Mar 7, 2022 at 15:17

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.