Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting ajax call per input

I have a working ajax call that I've made which sends a value to an endpoint for every input change. SO if the user is typing, it sends the call per keystroke.

I put a setTimeout around it for 2 seconds, which delays the call just fine. But the problem is it still sends a call for every keystroke.

I want to get it to where, after 2 seconds, it sends a call for what's been typed so far. If the user starts typing again maybe it would set again.

I"m just trying to send fewer keystrokes and make it to where when the user stops typing there's just a slight delay and call.

Here's the call now:

$('#input').on('input', function() {
  let _this = $(this);


  if (_this.val() === '') {
    return;
  } else {

    const searchResult = $(this).val();
    console.log(searchResult);
    //if I type "PLANT" the console shows "P" "PL" "PLA" "PLAN" "PLANT"

    //after 2 seconds, send searchResult via ajax
    setTimeout(function () {
        $.ajax({ url: '/endpoint', 
          data: {
            search_result:searchResult
          },
          "_token": "{{ csrf_token() }}",
          type: "POST", 
          success: successHandler 

        });
    }, 2000);
  }
});
like image 347
Whisou138 Avatar asked Sep 02 '25 03:09

Whisou138


1 Answers

You should debounce the ajax call. The idea is that the timeout is cleared if the user enters another value. That way the ajax call will only be made once after the user has stopped typing for the given timeout period (2 seconds for your case). That would look something like this:

var timeout;

$('#input').on('input', function() {
  let _this = $(this);


  if (_this.val() === '') {
    return;
  } else {

    const searchResult = $(this).val();
    console.log(searchResult);
    //if I type "PLANT" the console shows "P" "PL" "PLA" "PLAN" "PLANT"

    if (timeout) {
      clearTimeout(timeout);
    }
    
    //after 2 seconds, send searchResult via ajax
    timeout = setTimeout(function () {
        $.ajax({ url: '/endpoint', 
          data: {
            search_result:searchResult
          },
          "_token": "{{ csrf_token() }}",
          type: "POST", 
          success: successHandler 

        });
    }, 2000);
  }
});
like image 118
Cody S Avatar answered Sep 05 '25 00:09

Cody S