Josh
Josh

Reputation: 3120

Select2 Ajax Laravel - results not showing

JS

$("#location").select2({
        ajax: {
        url: "/search/locations",
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            q: params.term, // search term
          };
        },
        processResults: function (data) {
            return {
            results: data
            };
        },
        cache: true
      },
        minimumInputLength: 1,
        placeholder: function(){
        $(this).data('placeholder');
        }
      });

Controller

 public function searchLocations()
        {
            $q = Input::get('q');
            $results = Location::where('suburb', 'LIKE', '%'. $q . '%')
               ->orWhere('state', 'LIKE', '%'. $q . '%')
               ->orWhere('postcode', 'LIKE', '%'. $q . '%')
               ->get();
            return Response::json( $results ); 
        }

I can see the ajax request being made, and recieving data back, but it doesn't show the results. I'm using the latest version of Select2 (v4.0.2)

Upvotes: 2

Views: 3191

Answers (1)

apokryfos
apokryfos

Reputation: 40683

When you're loading custom data from a remote source, Select2 doesn't typically know what to do with them. You'll need to specify how each result is formatted by setting a templateSelection for the options and a templateResult for the selected option like so:

function locationResultTemplater(location) {
      return location.suburb + " " + location.state + " " + location.postcode;
} 

function locationSelectionTemplater(location) {
      if (typeof location.suburb !== "undefined") {
          return locationResultTemplater(location);
      }
      return location.text; // I think its either text or label, not sure.
}
$("#location").select2({
        ajax: {
        url: "/search/locations",
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            q: params.term, // search term
          };
        },
        processResults: function (data) {
            return {
            results: data
            };
        },
        cache: true
      },
        minimumInputLength: 1,
        placeholder: function(){
           $(this).data('placeholder');
        },
        templateResult: locationResultTemplater,
        templateSelection: locationSelectionTemplater

  });

Note that in order to return HTML mark-up instead just plain text you'll need to have the template function return a jQuery object selector e.g. return $("<div class='styleme'>Content</div>);

Upvotes: 3

Related Questions