Search code examples
javascriptajaxmarionette

How to call external method from nested ajax (success) method?


I need to call onSuccessLogin method from ajax success method, or put response as argument into onSuccessLogin. Thank you for answers.

submit: function (form) {

      $.ajax({
        type: "post",
        url: "/login",
        data: {
          login: $(form).find('#login').val(),
          password: $(form).find('#password').val(),
          deviceType: environmentInfo.browser,
          sdkVersion: environmentInfo.browserVersion,
          osVersion: environmentInfo.OS
        },

        success: function(res) {
          localStorage.setItem("languagesList", res);
          //how to call onSuccessLogin method from here?
        },

    	//Another implementation
        // success: this.onSuccessLogin(res), - dosen't work, if I want put response from ajax into this method call

        error: this.onErrorLogin
      });
    },

onSuccessLogin: function () {
  //localStorage.setItem("languagesList", res); get response from second implementation
  window.location = "/";
}


Solution

  • By creating a reference (that can be seen from the scope of AJAX success callback) to the object holding onSuccessLogin.

    Inside the submit method (as a sibling of onSuccessLogin) that object is this.

    Also see MDN reference on ES6 Arrow functions - abstraction for binding this to enclosing scope.

    submit: function (form) {
    
          var self = this;
      
          $.ajax({
            type: "post",
            url: "/login",
            data: {
              login: $(form).find('#login').val(),
              password: $(form).find('#password').val(),
              deviceType: environmentInfo.browser,
              sdkVersion: environmentInfo.browserVersion,
              osVersion: environmentInfo.OS
            },
    
            success: function(res) {
              localStorage.setItem("languagesList", res);
              self.onSuccessLogin();
            },
    
        	//Another implementation
            // success: this.onSuccessLogin(res), - dosen't work, if I want put response from ajax into this method call
    
            error: this.onErrorLogin
          });
        },
    
    onSuccessLogin: function () {
      //localStorage.setItem("languagesList", res); get response from second implementation
      window.location = "/";
    }