{"id":2283,"date":"2017-03-25T18:09:52","date_gmt":"2017-03-25T12:39:52","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=2283"},"modified":"2017-03-28T15:38:12","modified_gmt":"2017-03-28T10:08:12","slug":"abort-ajax-requests-using-jquery","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/abort-ajax-requests-using-jquery\/","title":{"rendered":"[ Solved &#8211; 11 Answers ] JQUERY &#8211; JAVASCRIPT &#8211; Abort Ajax requests using jQuery"},"content":{"rendered":"<p><label class=\"label label-Warning\">PROBLEM<\/label><\/p>\n<ul>\n<li>How to cancel\/abort jQuery AJAX request?<\/li>\n<\/ul>\n<p><label class=\"label label-info\">SOLUTION :1<\/label><\/p>\n<ul>\n<li>jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so we can use abort().<\/li>\n<li>abort Method (MSDN)- Cancels the current HTTP request.<\/li>\n<li>abort() (MDN) &#8211; If the request has been sent already, this method will abort the request.<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">var xhr = $.ajax({<br\/>    type: &quot;POST&quot;,<br\/>    url: &quot;some.php&quot;,<br\/>    data: &quot;name=John&amp;location=Boston&quot;,<br\/>    success: function(msg){<br\/>       alert( &quot;Data Saved: &quot; + msg );<br\/>    }<br\/>});<br\/><br\/>\/\/kill the request<br\/>xhr.abort()<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<h4 id=\"update\"><span style=\"color: #800000;\"><strong>UPDATE:<\/strong><\/span><\/h4>\n<ul>\n<li>As of jQuery 1.5 the returned object is a wrapper for the native XMLHttpRequest object called jqXHR.<\/li>\n<li>This object appears to expose all of the native properties and methods.<\/li>\n<\/ul>\n<p><label class=\"label label-info\">SOLUTION :2<\/label><\/p>\n<ul>\n<li>The jquery ajax method returns a XMLHttpRequest object. we can use this object to cancel the request.<\/li>\n<li>The XMLHttpRequest has a abort method, which cancels the request, but if the request has already been sent to the server then the server will process the request even if we abort the request but the client will not wait for\/handle the response.<\/li>\n<li>The xhr object also contains a readyState which contains the state of the request(UNSENT-0, OPENED-1, HEADERS_RECEIVED-2, LOADING-3 and DONE-4).<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">$(document).ready(<br\/>    var xhr;<br\/><br\/>    var fn = function(){<br\/>        if(xhr &amp;&amp; xhr.readyState != 4){<br\/>            xhr.abort();<br\/>        }<br\/><br\/>    var interval = setInterval(fn, 500);<br\/>);<\/code><\/pre> <\/div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\"> xhr = $.ajax({<br\/>            url: &#039;ajax\/progress.ftl&#039;,<br\/>            success: function(data) {<br\/>                \/\/do something<br\/>            }<br\/>        });<br\/>    };<\/code><\/pre> <\/div>\n<p><label class=\"label label-info\">SOLUTION :3<\/label><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">$.xhrPool = [];<br\/><br\/>$.xhrPool.abortAll = function() {<br\/>  \/* Original example used _underscore api<br\/>    _.each(this, function(jqXHR) {<br\/>        jqXHR.abort();<br\/>    });<br\/>  *\/<br\/>    $.each(this, function(jqXHR) { <br\/>        jqXHR.abort(); <br\/>    });<br\/>};<br\/><br\/>$.ajaxSetup({<br\/>    beforeSend: function(jqXHR) {<br\/>        $.xhrPool.push(jqXHR);<br\/>    }<br\/>});<\/code><\/pre> <\/div>\n<p><label class=\"label label-info\">SOLUTION :4<\/label><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">$.xhrPool = [];<br\/><br\/>$.xhrPool.abortAll = function() {<br\/>    $.each(this, function(jqXHR) { <br\/>        jqXHR.abort(); <br\/>    });<br\/>};<br\/><br\/>$.ajaxSetup({<br\/>    beforeSend: function(jqXHR) {<br\/>        $.xhrPool.push(jqXHR);<br\/>    },<br\/>    complete: function(jqXHR) {<br\/>        var index = $.xhrPool.indexOf(jqXHR);<br\/>        if (index &gt; -1) {<br\/>            $.xhrPool.splice(index, 1);<br\/>        }<br\/>    }<br\/>});<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<p><label class=\"label label-info\">SOLUTION :5<\/label><\/p>\n<p>AJAX requests may not complete in the order they were started. Instead of aborting, we can choose to ignore all AJAX responses except for the most recent one:<\/p>\n<ul>\n<li>Create a counter<\/li>\n<li>Increment the counter when we initiate AJAX request<\/li>\n<li>Use the current value of counter to &#8220;stamp&#8221; the request<\/li>\n<li>In the success callback compare the stamp with the counter to check if it was the most recent request.<\/li>\n<\/ul>\n<h4 id=\"rough-outline-of-code\"><span style=\"color: #800080;\">Rough outline of code:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">var xhrCount = 0;<br\/>function sendXHR() {<br\/>    \/\/ sequence number for the current invocation of function<br\/>    var seqNumber = ++xhrCount;<br\/>    $.post(&quot;\/echo\/json\/&quot;, { delay: Math.floor(Math.random() * 5) }, function() {<br\/>        \/\/ this works because of the way closures work<br\/>        if (seqNumber === xhrCount) {<br\/>            console.log(&quot;Process the response&quot;);<br\/>        } else {<br\/>            console.log(&quot;Ignore the response&quot;);<\/code><\/pre> <\/div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\"> }<br\/>    });<br\/>}<br\/>sendXHR();<br\/>sendXHR();<br\/>sendXHR();<br\/>\/\/ AJAX requests complete in any order but only the last <br\/>\/\/ one will trigger &quot;Process the response&quot; message<\/code><\/pre> <\/div>\n<p><label class=\"label label-info\">SOLUTION :6<\/label><\/p>\n<p>Here there are three different solution approaches.<\/p>\n<ul>\n<li>Cancel the request<\/li>\n<li>Execute all request but only processes the result of the last submit<\/li>\n<li>Prevents new requests as long as another one is still pending<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">&lt;!DOCTYPE html&gt;<br\/>&lt;html&gt;<br\/><br\/>&lt;head&gt;<br\/>    &lt;title&gt;AJAX Test&lt;\/title&gt;<br\/>    &lt;script src=&quot;http:\/\/code.jquery.com\/jquery.min.js&quot;&gt;&lt;\/script&gt;<br\/>    &lt;script&gt;<br\/>        var Ajax1 = {<br\/>            call: function () {<br\/>                if (typeof this.xhr !== &#039;undefined&#039;)<br\/>                    this.xhr.abort();<br\/>                this.xhr = $.ajax({<\/code><\/pre> <\/div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">url: &#039;your\/long\/running\/request\/path&#039;,<br\/>                    type: &#039;GET&#039;,<br\/>                    success: function (data) {<br\/>                        \/\/process response<br\/>                    }<br\/>                });<br\/>            }<br\/>        };<br\/>        var Ajax2 = {<br\/>            counter: 0,<br\/>            call: function () {<br\/>                var self = this,<br\/>                    seq = ++this.counter;<br\/>                $.ajax({<br\/>                    url: &#039;your\/long\/running\/request\/path&#039;,<br\/>                    type: &#039;GET&#039;,<br\/>                    success: function (data) {<br\/>                        if (seq === self.counter) {<br\/>                            \/\/process response<\/code><\/pre> <\/div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\"> }<br\/>                    }<br\/>                });<br\/>            }<br\/>        };<br\/>        var Ajax3 = {<br\/>            active: false,<br\/>            call: function () {<br\/>                if (this.active === false) {<br\/>                    this.active = true;<br\/>                    var self = this;<br\/>                    $.ajax({<br\/>                        url: &#039;your\/long\/running\/request\/path&#039;,<br\/>                        type: &#039;GET&#039;,<br\/>                        success: function (data) {<br\/>                            \/\/process response<br\/>                        },<\/code><\/pre> <\/div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">complete: function () {<br\/>                            self.active = false;<br\/>                        }<br\/>                    });<br\/>                }<br\/>            }<br\/>        };<br\/>        $(function () {<br\/>            $(&#039;#button&#039;).click(function (e) {<br\/>                Ajax3.call();<br\/>            });<br\/>        })<br\/>    &lt;\/script&gt;<br\/>&lt;\/head&gt;<br\/><br\/>&lt;body&gt;<\/code><\/pre> <\/div>\n<p><label class=\"label label-info\">SOLUTION :7<\/label><\/p>\n<ul>\n<li>Here is the solution for Abort Ajax requests using jQuery:<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">var $request;<br\/>if ($request != null){ <br\/>    $request.abort();<br\/>    $request = null;<br\/>}<br\/><br\/>$request = $.ajax({<br\/>    type : &quot;POST&quot;, \/\/TODO: Must be changed to POST<br\/>    url : &quot;yourfile.php&quot;,<br\/>    data : &quot;data&quot;<br\/>    }).done(function(msg) {<br\/>        alert(msg);<br\/>    });<\/code><\/pre> <\/div>\n<p>If we check an if statement to check whether the ajax request is null or not.<\/p>\n<p><label class=\"label label-info\">SOLUTION :8<\/label><\/p>\n<ul>\n<li>We needed to cancel pending requests that may have taken longer than the latest\/most current request.<\/li>\n<\/ul>\n<h4 id=\"we-can-use-something-like-this\"><span style=\"color: #000000;\">we can use something like this:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">\/\/On document ready<br\/>var ajax_inprocess = false;<br\/><br\/>$(document).ajaxStart(function() {<br\/>ajax_inprocess = true;<br\/>});<br\/><br\/>$(document).ajaxStop(function() {<br\/>ajax_inprocess = false;<br\/>});<br\/><br\/>\/\/Call for new request<\/code><\/pre> <\/div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">\/\/Snippet from live search function<br\/>if (ajax_inprocess == true)<br\/>{<br\/>    request.abort();<br\/>}<\/code><\/pre> <\/div>\n<p><label class=\"label label-info\">SOLUTION :9<\/label><\/p>\n<ul>\n<li>The request is aborted on the client-side, the server will still process the request.<\/li>\n<li>This creates unnecessary load on the server because it&#8217;s doing work that we&#8217;ve quit listening to on the front-end.<\/li>\n<li>The problem will trying to solve (that others may run in to as well) is that when the user entered information in an input field, we wanted to fire off a request for a Google Instant type of feel.<\/li>\n<li>To avoid unnecessary requests and to maintain the front-end.<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">var xhrQueue = [];<br\/>var xhrCount = 0;<br\/><br\/>$(&#039;#search_q&#039;).keyup(function(){<br\/><br\/>    xhrQueue.push(xhrCount);<br\/><br\/>    setTimeout(function(){<br\/><br\/>        xhrCount = ++xhrCount;<\/code><\/pre> <\/div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">if (xhrCount === xhrQueue.length) {<br\/>            \/\/ Fire Your XHR \/\/<br\/>        }<br\/><br\/>    }, 150);<br\/><br\/>});<\/code><\/pre> <\/div>\n<p>This will essentially send one request every 150ms (a variable that we can customize for our own needs).<\/p>\n<p><label class=\"label label-info\">SOLUTION :10<\/label><\/p>\n<ul>\n<li>Just call xhr.abort() whether it&#8217;s jquery ajax object or native XMLHTTPRequest object.<\/li>\n<\/ul>\n<h4 id=\"example\"><span style=\"color: #3366ff;\">example:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">\/\/jQuery ajax<br\/>$(document).ready(<br\/>    var xhr = $.get(&#039;\/server&#039;);<br\/>    setTimeout(function(){xhr.abort();}, 2000);<br\/>);<br\/><br\/>\/\/native XMLHTTPRequest<br\/>var xhr = new XMLHttpRequest();<br\/>xhr.open(&#039;GET&#039;,&#039;\/server&#039;,true);<br\/>xhr.send();<br\/>setTimeout(function(){xhr.abort();}, 2000);<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<p><label class=\"label label-info\">SOLUTION :11<\/label><\/p>\n<ul>\n<li>The below example demonstrates how to cancel an AJAX request&#8211; if data is not returned from the server within a predefined wait time.<\/li>\n<\/ul>\n<h4 id=\"html\"><span style=\"color: #993366;\">HTML :<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">&lt;div id=&quot;info&quot;&gt;&lt;\/div&gt;<\/code><\/pre> <\/div>\n<h4 id=\"js-code\"><span style=\"color: #333399;\">JS CODE:<\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">var isDataReceived= false, waitTime= 1000; <br\/>$(function() {<br\/>    \/\/ Ajax request sent.<br\/>     var xhr= $.ajax({<br\/>      url: &#039;http:\/\/api.joind.in\/v2.1\/talks\/10889&#039;,<\/code><\/pre> <\/div>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">jQuery Code<\/span> <\/div> <pre class=\"language-javascript code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-javascript code-embed-code\">data: {<br\/>         format: &#039;json&#039;<br\/>      },     <br\/>      dataType: &#039;jsonp&#039;,<br\/>      success: function(data) {      <br\/>        isDataReceived= true;<br\/>        $(&#039;#info&#039;).text(data.talks[0].talk_title);        <br\/>      },<br\/>      type: &#039;GET&#039;<br\/>   });<br\/>   \/\/ Cancel ajax request if data is not loaded within 1sec.<br\/>   setTimeout(function(){<br\/>     if(!isDataReceived)<br\/>     xhr.abort();     <br\/>   },waitTime);   <br\/>});<\/code><\/pre> <\/div>\n","protected":false},"excerpt":{"rendered":"<p>PROBLEM How to cancel\/abort jQuery AJAX request? SOLUTION :1 jQuery Ajax methods return an XMLHttpRequest (or the equivalent) object, so we can use abort(). abort Method (MSDN)- Cancels the current HTTP request. abort() (MDN) &#8211; If the request has been sent already, this method will abort the request. [ad type=&#8221;banner&#8221;] UPDATE: As of jQuery 1.5 [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[275],"tags":[4966,4973,4968,4977,4965,4978,4976,4969,4970,4967,4964,4974,4963,4975,4980,4979,4971,4972],"class_list":["post-2283","post","type-post","status-publish","format-standard","hentry","category-javascript","tag-ajaxstop","tag-abort-all-ajax-requests","tag-abort-all-pending-jquery-ajax-requests","tag-abort-previous-ajax-request-on-new-request","tag-aborting-an-ajax-request","tag-cancel-ajax-request-angularjs","tag-cancel-ajax-request-server-side","tag-cancel-or-abort-jquery-ajax-request","tag-how-to-abort-a-ajax-call-before-calling-the-same-again","tag-how-to-abort-a-previous-ajax-request-in-jquery","tag-how-to-cancelabort-jquery-ajax-request","tag-how-to-stop-ajax-call-in-jquery","tag-javascript-abort-ajax-requests-using-jquery","tag-jquery-ajax-cancel-previous-request","tag-jqxhr-abort","tag-stop-ajax-request-onclick","tag-stop-all-active-ajax-requests","tag-try-to-cancel-all-jquery-ajax-requests-currently-running"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/2283","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=2283"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/2283\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=2283"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=2283"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=2283"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}