0

I have the following code in JavaScript and jQuery with an integrated ajax request. Question: Why is it possible to call the inner function success1() but it is not possible to call this.success2() ? Any solution proposals for this problem?

function myfuntion() {
    this.url = "www.example.com/ajax.php";
    var success1 = function (data) {
        alert("SUCCESS1");
    }
    this.success2 = function (data) {
        alert("SUCCESS2");
    }
    this.send = function () {
        $.ajax({
            type: "POST",
            url: this.url,
            dataType: "html"
        }).done(function (data) {
            success1(data);
            this.success2(data);
        });
    }
}
var test = new myfunction().send();
2

1 Answer 1

1

As other commented, the context of this inside the send function is changed, so that's why your success2 function is not calling. You should save myFunction context in a variable and use that variable to refer this context.

Try this:

function myfuntion() {
    var self = this;                // taking the current context in a variable.

    self.url = "www.example.com/ajax.php";
    var success1 = function (data) {
        alert("SUCCESS1");
    }
    self.success2 = function (data) {
        alert("SUCCESS2");
    }
    self.send = function () {
        $.ajax({
            type: "POST",
            url: self.url,
            dataType: "html"
        }).done(function (data) {
            success1(data);
            self.success2(data);
        });
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.