Search code examples
jqueryajaxjquery-select2jquery-select2-4

Select2 multiple calls to ajax


I have a problem with the Select2 component in this code:

$("#group_select_name").select2({
  placeholder: "Select a Group",
  allowClear: true,
  ajax: {
    type: "GET",
    url: "../contactGroup",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    processResults: function(data) {
      return {
        results: $.map(data, function(obj) {
          console.log("update 2")
          return {
            id: (obj.id),
            text: (obj.name)
          };
        })
      };
    },
  }
});

Everything works fine, but when I try to search for something using the search field, the component make multiple undesired AJAX requests to the server. In the console of the browser I see thousands of "update 2".

The version of Select is the 4.0.3. Any suggestions?


Solution

  • This is because the componente make a request for each key pressed. You can define a delay to start the request, like described in the official doc:

    By default, Select2 will trigger a new AJAX request whenever the user changes their search term. You can set a time limit for debouncing requests using the ajax.delay option.

    https://select2.github.io/options.html#a-request-is-being-triggered-on-every-key-stroke-can-i-delay-th

    $('select').select2({
      ajax: {
        url: '/example/api',
        delay: 250
      }
    });
    

    [EDIT]

    Your console.log is inside the map function, that will be executed for each element in result after each request.