Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stop jquery ajax request sent via $.get?

i am making a ajax request using $.get as soon as the user types a character in the input box i want to abort the previous ajax calls and then make the new one, is there a way?

edit

solved!

i just found out that $.get is a shorthand way to $.ajax and hence it returns a XHR and so we can call abort on that variable.

like image 381
Shaheer Avatar asked Nov 12 '10 10:11

Shaheer


People also ask

How do I stop XHR request?

The XMLHttpRequest. abort() method aborts the request if it has already been sent. When a request is aborted, its readyState is changed to XMLHttpRequest. UNSENT (0) and the request's status code is set to 0.

How do I know if ajax request is complete?

The ajaxStop() method specifies a function to run when ALL AJAX requests have completed. When an AJAX request completes, jQuery checks if there are any more AJAX requests. The function specified with the ajaxStop() method will run if no other requests are pending.

What does ajax GET request do?

An AJAX request is a request made by an AJAX application. Typically, it is an HTTP request made by (browser-resident) Javascript that uses XML to encode the request data and/or response data.


1 Answers

You can use .abort() on XMLHttpRequest that $.get returns.

var req = $.get('ajax/test.html', function(data) {
            $('.result').html(data);
            alert('Load was performed.');
          });

//Abort request
req.abort()

From jQuery.ajax() documentation:

The $.ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option. The returned object can generally be discarded, but does provide a lower-level interface for observing and manipulating the request. In particular, calling .abort() on the object will halt the request before it completes.

More on .abort(): XMLHttpRequest.abort()

There is also jQuery plugin AjaxQueue for handling multiple Ajax request made in parallel.

like image 177
thaedal Avatar answered Sep 23 '22 00:09

thaedal