Marc J Marc J - 7 months ago 45
Javascript Question

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();

Answer

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/');