Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i stop ajax request (don't wait untill response come)?

If I use Ajax to send request and this request take long time ..... if I want to send anther request what should I do?

the current behaviour the second request (I did) waiting until the first request get with response.

NOTE : i want to do this behaviour on whole application (any new request execute immediately not wait the old one to be finished firstly) My application using (Ajax + PHP + jQuery + Symfony)

Assume that is the first request take long time:

$.ajax
({
    type: "GET",
    url: url1,
    success: function (html)
    {
       // do some thing  
    }
});

In any time I want this request to execute and terminate the first one.

$.ajax
({
    type: "POST",
    url: url,
    success: function (html)
    {
       // do some thing else 
    }
});

var xhrReq;
xhrReq = $.ajax(...);

// then if you want to stop the rqest and exit use :

 xhrReq.abort();
like image 1000
Sameh Serag Avatar asked Dec 27 '22 07:12

Sameh Serag


2 Answers

It’s sort of a manual process, but you can add a global xhr object and test it on each request. If the readystate is "loading", abort it:

var xhr;
var loadUrl = function(url) {
    if ( xhr && xhr.readyState > 0 && xhr.readyState < 4 ) {
        // there is a request in the pipe, abort
        xhr.abort();    
    }
    xhr = $.get(url, function() {
        console.log('success', this);
    });
};

loadUrl('/ajax/');
like image 52
David Hellsing Avatar answered Feb 13 '23 20:02

David Hellsing


The XMLHttpRequest object has an abort function. You can use setTimeout to abort a request that is taking too long.

EDIT: In the case you do not want to use a timer, and a new event occurs that should abort the prior request, then the event handler should do the following

if(!this.request) return;  // request contains the XMLHttpRequest
this.request.onreadystatechange = function() {};
if(this.request.readyState != 4) {
    this.request.abort();
}

Then after that you can create the new XMLHttpRequest object.

like image 21
yas Avatar answered Feb 13 '23 20:02

yas