Pages

Friday, 8 June 2012

How to abort an AJAX call using jQuery?

There may be situations where you need to cancel a running AJAX request before it ends. It's usually in cases where the user might perform an action, which sets of an AJAX request, several times within a short time period.

A good example of this is auto-complete functionality for a search box, where you might try to help the user by finding related search terms based on their current input, by making an AJAX request each time they press a key in the search field. In that case, it's very likely that the user types faster than your AJAX request can be performed and therefore you would want to abort any non-finished requests, before starting the next one.

Consider the following example:

<input type="button" name="btnDoRequest" value="Start" onclick="PerformSimpleCalculation();" />
<script type="text/javascript">

function PerformSimpleCalculation()
{
        $.get("/tests/calc.php", function(data, textStatus)
        {
                alert(data);
        });
}
</script>

It requests a PHP script which is doing a very complicated calculation (as you will see from the result), which means that it usually takes ~3 seconds to finish. Now, try the example and push the button several times after each other. The same "calculation" will be performed multiple times and the result will also be displayed multiple times (with a 3 second delay).

Fortunately, a call to the get() method and pretty much any other jQuery AJAX method, returns an object which, among others, contains an abort() method. We can save this reference and then call the abort() method on it if needed. Have a look at this slightly modified example:

<input type="button" name="btnDoRequest" value="Start" onclick="PerformAbortableCalculation();" />
<script type="text/javascript">

var calculationRequest = null;

function PerformAbortableCalculation()
{
        if(calculationRequest != null)
                calculationRequest.abort();
        calculationRequest = $.get("/tests/calc.php", function(data, textStatus)
        {
                alert(data);
        });
}
</script>

We start off by defining a common variable for containing the request reference. In the PerformAbortableCalculation() method, we assign the return value of the get() call to this variable, but before we do so, we check to see if it's null (the method hasn't been used yet) and if not, we call the abort() method on it. If you try this example and click several times, you will see that no matter how many times you click the button, it only executes the callback function once.

No comments:

Post a Comment