3

I have a search box in my application. In which I have to show results while user typing the word in search box. For this I need to abort all previous requests and show the result of last request in grid.

Because I am using grid, grid "beforeSend" event will override jquery beforeSend event. So I used below code,

<script type="text/javascript">
$(function () {
    $.xhrPool = [];
    grid.Adaptor.prototype.beforeSend = function (jqXHR) {
        $.xhrPool.push(jqXHR);
    }
    $.xhrPool.abortAll = function () {
        $(this).each(function (i, jqXHR) { 
            jqXHR.abort();  
            $.xhrPool.splice(i, 1);
        });
    }
    $.ajaxSetup({
        complete: function (jqXHR) {
            var i = $.xhrPool.indexOf(jqXHR); 
            if (i > -1) $.xhrPool.splice(i, 1); 
        }
    });
})

However, I can push the request in xhrPool, but I can't abort the previous requests.

Note $.xhrPool.abortAll = function () { this is not hitting when I place a breakpoint.

What I am missing here ?

Shesha
  • 1,857
  • 6
  • 21
  • 28

1 Answers1

1

I have to show results while user typing the word in search box. For this I need to abort all previous requests and show the result of last request in grid.

Your code:

$.ajaxSetup({
    complete: function (jqXHR) {
        var i = $.xhrPool.indexOf(jqXHR); 
        if (i > -1) $.xhrPool.splice(i, 1); 
    }
});

Won't do anything as this complete callback fires only when the request has got the response as success or error. So, aborting here doesn't make sense.

I would suggest you to use a timed setTimeout() in conjunction with clearTimeout():

$(function() {
  var time;

  $('input').keydown(function(e){

    if(time){ 
      // before hitting the ajax 
      // clear the timeout if there is/are
      clearTimeout(time); 
    } 

    time = setTimeout(function(){
      // here put the ajax code.
    },600);

  });

})
Jai
  • 74,255
  • 12
  • 74
  • 103
  • This is working when I add setTimeOut function. I need to confirm that I cannot abort previous ajax requests in ajaxSetup ? – Shesha Mar 22 '16 at 09:46
  • You can do that with in `beforeSend:callback`. – Jai Mar 22 '16 at 09:50
  • ok fine jai. I am using grid so, ajaxsetup beforeSend won't work for me. Thanks for the solution. :) :) – Shesha Mar 22 '16 at 09:56