How to cancel all other ajax requests?

123 Views Asked by At

I have a SPA website.

When I send request A, I find I clicked wrong link. So I click and send request B before complete request A. So I want to abort request A and all other requests. I tried XMLHttpRequest.abort(); but it is only abort request B.

Simple Source Code :

function link(){
const request=new XMLHttpRequest();
request.open('GET','//example.com/',true);
request.send();
request.onload=()=>{
console.log('Loaded');
}
}

Full Source Code :

link(to){
    const requeset=new XMLHttpRequest();
    request.open('GET','/api/window.location,true);
    request.send();
    request.onload=function(){
    console.log('hello!');
    }
}
2

There are 2 best solutions below

4
Levi Cole On BEST ANSWER

You can keep a reference to the previous request something like...

var lastRequest = null;

// Loop through all action buttons
document.querySelectorAll('button.action').forEach(button => {

    // Attach a click event listener
  button.addEventListener('click', event => {
    event.preventDefault();

        // If there was a previous request, kill it.
    if (lastRequest) {
      lastRequest.abort();
      lastRequest = null;
    }

        // Now make the new request and store the reference.
    lastRequest = new XMLHttpRequest();
    lastRequest.open('GET', 'https://reqres.in/api/users?delay=3');
    lastRequest.onload = () => {
      lastRequest = null; // We reset the last request reference on load.
    };
    lastRequest.send();
  });
})
<button class="action">Action 1</button>
<button class="action">Action 2</button>


UPDATE

function link(to) {

    // If there was a previous request, kill it.
    if (window._myLastLinkRequest) {
        window._myLastLinkRequest.abort();
        window._myLastLinkRequest = null;
    }


    const request = new XMLHttpRequest();
    
    request.open('GET','/api/' + window.location, true);
    request.onload = function() {
        console.log('hello!');
        window._myLastLinkRequest = null; // We reset the last request reference on load.
    };
    request.send();

    // Now store the reference to the new request.
    window._myLastLinkRequest = request;
}
0
mhaendler On

You should save your last request in some way.

If you are handling your request "B", you can check if there is still an ongoing request by checking the readyState of your previous xhr. In my exmaple it's

$previousHxr
//function to handle the xhr
if($previousHxr.readyState !== 4){
    $previousHxr.cancel();
}