Search code examples
javascriptjquery-select2

Clear Select2 before send ajax


How can I clear the last results, before Select2 starts a new ajax-call? (Without changing the original select2-files)

To reproduce:

  1. Select2 with ajax-function.
  2. Search anything.
  3. Search with other term.
  4. The old results of step 2 are still visible unitl the ajax-query of step 3 is ready.

Solution

  • Inside ajax data handler you can clear items:

    ajax: {
        type: "POST",
        url: '/echo/json/',
        dataType: 'json',
        data: function(params){
            console.log("ajax");
          // reset selection
          $('.select').val(null).trigger('change');
          var query = {
            search: params.term,
            items: data
          };
          return { json: JSON.stringify( query ) }
        },
        processResults: function (data, page) { 
            return { results: data.items };
        },
    }
    

    Here is a jsfiddle: https://jsfiddle.net/beaver71/jb07ehpq/