Quit get request as soon as you start another

2

In my ecommerce has a search field. As the user goes typing, it returns a list of products in a div below the search field. this is 100%

In the label I put an onkeyup that performs a function that searches the product list and displays. this is 100% too

My problem is that if the digital person "battery s5" for example will get 10 get synchronous, each result display will take ~ 1 seconds, the exportation of the product list in this example would take ~ 10 seconds

My question is if you have a new request to stop / break / kill the previous request

Follow below my get

$.ajax({
        url: "<?=$this->Html->url(array('controller' => 'busca', 'action' => 'searchanise'));?>",
        type: 'POST',
        async: false,
        data: {texto: text},
        success: function(data){
            retorno = JSON.parse(data);

            $("#searchanise").html(retorno);
        }

    });
    
asked by anonymous 12.03.2015 / 14:14

2 answers

1

I suggest creating a debouce function , a function that sends ajax requests not to each event but at each time interval. This way you avoid sending excessive orders.

Another alternative or complementary possibility is to have a variable that knows the last request, so that you do not receive the wrong answer if they come in a changed order.

If the list of possibilities is not too large you could pass this on to an object just when you load the page and do this functionality in JavaScript only.

debouce function, example:

function debounce(fn, delay) {
  var timer = null;
  return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}

$('input.username').keypress(debounce(function (event) {
  // do the Ajax request
}, 250));

This will only send the ajax request after 1/4 second of inactivity.

variable / flag with last request:

Using your code, put together a variable with the previous scope:

var ajaxID = 0;
$.ajax({
    url: "<?=$this->Html->url(array('controller' => 'busca', 'action' => 'searchanise'));?>",
    type: 'POST',
    async: false,
    data: {texto: text},
    beforeSend: function(){
        ajaxID++;
        this.ajaxID = ajaxID;
    },
    success: function(data){
        if (this.ajaxID != ajaxID) return; // descartar pois não é a ultima
        retorno = JSON.parse(data);
        $("#searchanise").html(retorno);
    }

});
    
12.03.2015 / 14:42
0

You can save the call get to a variable:

var request = $.ajax({
    type: 'POST',
    url: 'someurl',
    success: function(result){}
});

So every time you make a request, just check the request variable. If it is not null or indefinite, just give abort before starting the new request:

request.abort();
    
12.03.2015 / 14:44