0

I create class. Everything work, but success function not redirect. Why?

class Ajax {
  constructor(url, method, dataType, reDirect, alert) {
    this.url = url,
      this.method = method,
      this.dataType = dataType,
      this.reDirect = reDirect,
      this.alert = alert
  }

  getAJAX() {
    $.ajax({
      url: this.url,
      method: this.method,
      dataType: this.dataType,
      success: function(result) {
        window.location = this.reDirect
      },
      error: function(result) {
        alert(this.alert)
      }
    })
  }
}

This is how I call a method from the class:

const clearConf = new Ajax('/ConfigurationHistories/ClearList', 'GET', 'text', '/ConfigurationHistories/Index', 'Not clear list.')
clearConf.getAJAX()
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Kamil M
  • 55
  • 1
  • 6
  • `this` in the `success` handler function does not contain a reference to your `Ajax` class. You need to cache that outside of the handler or use an arrow function (assuming you don't need to support IE at all). See the duplicate for more information – Rory McCrossan Aug 08 '19 at 13:10

1 Answers1

0

Because this is reassigned in the success function. Use an arrow function:

success: () => {
  window.location = this.reDirect;
}

Or use bind:

success: function() {
  window.location = this.reDirect;
}.bind(this);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79