Problem with asynchronous request jquery



  • That's a problem. I'm writing a smart search on the site, and I'm sending a request for a sample of buds.
    For example, I put the word "story" in, then I put the letter "l" in, and I'm leaving a request with the word "story."
    After that, a request with the word "post" comes faster, and after it comes the answer to the "st" request and, accordingly, closes the answer I need. Any exits?
    Here's the code.

    $(document).on('keyup', '#fastcat', function () {
    
    var ad = $(this);
    $.ajax({
        type: "GET",
        url: "/ajax/fastcat?q=" + ad.val(),
        beforeSend: function () {
            if (ad.val().length > 1) {
                $(".fastcat_auto").removeClass('visible');
                $('.fastcat_div .loader').show();
            }
    
        },
        success: function (html) {
            $('.fastcat_div .loader').hide();
            if (html != 'fail') {
                $('.fastcat_auto').html('');
                $('.fastcat_auto').html(html);
                $(".fastcat_auto").addClass('visible');
            } else {
                if (ad.val().length > 1) {
                    $('.fastcat_auto').html('<ul><li>Ничего не найдено.</li> </ul>');
                    $(".fastcat_auto").addClass('visible');
                }
    
            }
        }
    });
    

    });



  • It's simple. When you get the answer, check that you sent if it matches the current input value.

    Pseudocod:

    function search(){
      var query = $edit.val();
      $.ajax("?search="+query)
        .done(data => if(query!=$edit.val()) return; pupulate(data););
    }
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2