Home > Net >  Canceling the incoming request with a button
Canceling the incoming request with a button

Time:11-18

When I switch to a menu, I get data from the API. While this data is still typing pendig in DevTools, I click the Filter button and search for another data. The data I'm looking for comes to my table. But when the pending data comes, the data I search for disappears.

Command line where I get the data

  protected loadData = (params) => {
    $.ajax({
        method: 'GET',
        url: this.tableUrl,
        data: params.data,
        beforeSend: (request) => {
            request.setRequestHeader('Authorization', `Bearer ${this.authService.getToken()}`);
        }
    }).done((response) => {
        params.success(response);
    });
}

The requests I received above. The top request takes about 40 seconds. The bottom takes 1 second. It fetches data in 1 second. Since the other takes 40 seconds, other data is added on top of the data that comes in 1 second after 39 seconds. I need to cancel requests that say "referenceTumList?PageIndex=0&PageSize=10" while I am filtering.

CodePudding user response:

You can cancel ajax call like this

xhrReq: any;

protected loadData = (params) => {

if(this.xhrReq){
    this.xhrReq.abort();
}

this.xhrReq = $.ajax({
    method: 'GET',
    url: this.tableUrl,
    data: params.data,
    beforeSend: (request) => {
        request.setRequestHeader('Authorization', `Bearer ${this.authService.getToken()}`);
    }
}).done((response) => {
    params.success(response);
});
}

if you want to cancel call on button click

onButtonClick(){
    if(this.xhrReq){
        this.xhrReq.abort();
    }
}
  • Related