crashfellow
crashfellow

Reputation: 31

Search2 - Ajax results with no search

I'm using ajax to pull in data from a php file (which returns json).

I'm wondering, can you have results pulled from Ajax and loads on click without having to search? so essentially you click the field, it drops down with all the elements from Ajax. Couldn't find in the documentation.

Code:

 jQuery('.producttypesajax').select2({
    allowClear: true,
    placeholder: {
    id: '',
      text: 'Search by Product Type'
    },
ajax: {
  url: base + '/appProductTypeSearch.php',
  dataType: 'json',
  delay: 250,
  data: function( params ) {
    return {
      q: params.term // search term
    };
  },
  processResults: function( data) {
    return {
      results: data
    };
  },
  cache: true
},
minimumInputLength: 1
  });

  jQuery('.producttypesajax').on('select2:select', function (e) {
var data = e.params.data;
 });

https://select2.org/data-sources/ajax

Upvotes: 3

Views: 2358

Answers (1)

A.Terra
A.Terra

Reputation: 168

I believe there's no native solution for this, but I managed to do it somehow.

Since Select2 accepts Arrays as a data source, you can make an Ajax request returning your Json object and use it as an "Array".

Sample code:

$.ajax({
     url: url,
     type: 'get',
     dataType: 'json',
     success: function (jsonObject){
        $('#mySelect').select2({ data: jsonObject });
     }
});

It worked for me. Hope it helps.

Upvotes: 3

Related Questions