简体   繁体   中英

How to get Select2 Ajax working with Algolia and transport

I'm building a typeahead search field and I'm running into issues. I'm not quite sure what the proper way is to get the results to display. When I type in the field, the results are found but the field isn't updating. Here's my code:

<select name='vendor_order[vendor_id]' id='vendor-select' class="form-control">
    <option>Choose a vendor</option>
 </select>
 <script src="//cdn.jsdelivr.net/algoliasearch/3/algoliasearch.min.js"></script>
<script type='text/javascript'>
var $select = $('#vendor-select');
var client = algoliasearch('[INDEX]', '[PUBLISHABLE_KEY]');
var index = client.initIndex('Vendor_development');

// function formatSearchResult(res){
//    console.log('format search result: ', res);
// }

$select.select2({
    ajax: {
       // Custom transport to call Algolia's API
       transport: function(params) {
          var q = params.data.query.term;
          index.search(q, function searchDone(err, content) {
              if( !err ){
                  params.results(content);
              }
          });
      },
      // build Algolia's query parameters
      data: function(term, page) {
          return { query: term, hitsPerPage: 10, page: (page - 1) };
      },
      // return Algolia's results
      results: function(data, page) {
              return { results: data.hits };
              // I noticed that data.hits objects have objectID instead of id attribute which select2 needs
              // However even with a test array where the objects have an `id` attribute, it doesn't work. 
      },
      cache: true
  },
  "language": {
      "noResults": function(){
          return "No matching vendor. <a data-toggle='modal' data-target='#create-vendor-modal'>Create a new one</a>."
       }
  },
  escapeMarkup: function (markup) { return markup; }, 
  minimumInputLength: 1//,
  // templateResult: formatSearchResult 
  // templateSelection: formatRepoSelection 
});
</script>

What am I missing?!?!?

Your issue is in the results functions, you do return { return { .... } } .

Here is a working JSFiddle with Select2 v3 and JSFiddle with Select2 v4 if you want to play with :)

So @redox got the old version of Algolia search working with the old Select2 but the issue I was running into was the version of Select2. If you want the latest version of Algolia search to work with Select 2 (version 4+) I've put together an updated JSFiddle:

http://jsfiddle.net/biznickman/r1h3afm9

Here's the full code:

var algolia = algoliasearch('YE0A9ATLJG', '1abceba46dace8485375bc325f0144b5');
var index = algolia.initIndex('Contact_development');

$(document).ready(function() {
    $('#test').select2({
      placeholder: {
        id: '-1', // the value of the option
        text: 'Select A Contact'
      },
      ajax: {
        transport: function(params,success,failure) {
          var q = params.data.query.term;
          index.search(q, function searchDone(err, content) {
            if( !err ){
              success(params.results(content));
            }
          });
        },
        // build Algolia's query parameters
        data: function(term, page) {
          return { query: term, hitsPerPage: 10, page: (page - 1) };
        },
        // return Algolia's results
        results: function(data, page) {
          return {
            results: data.hits
          };
        }
      },
      escapeMarkup: function (markup) { return markup; },
      minimumInputLength: 1,
      templateSelection: function(contact){
        if( contact.id=='-1' || contact.loading == true ){
            return contact.text;
        }else{
          return contact._highlightResult.email.value;
        }
      },
      templateResult: function(contact){
        if( contact.id=='-1' || contact.loading == true ){
            return contact.text;
        }else{
          return "<div class='select2-user-result'>" +
                contact._highlightResult.name.value + " (" + contact._highlightResult.company.value + ")" +
                '<br />' + 
                '<small class="text-muted">' + contact._highlightResult.email.value + '</small>' +
                "</div>"; 
        }
      },
      "language": {
          "noResults": function(){
              return "No matching vendor. <a data-toggle='modal' data-target='#create-vendor-modal'>Create a new one</a>."
           }
      },
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM