0

Html:

<div id="suggestionsearch" class="form-group">
 <input id="searchinput" type="text" class="form-control typeahead" placeholder="Search...">
</div>

Php controller:

public function searchlive(Request $request)
    {

        $term = $request->term;
        $productindex = Product::where('product_name', 'LIKE', '%' . $term . '%')->take(5)->get();
        $results = array();
        foreach ($productindex as $key => $value) {
            $results[]= ['id'=>$value->id, 'value'=>$value->product_name];
        }
        return Response()->json($results);
}

jquery (working code):

var substringMatcher = function(strs) {
  return function findMatches(q, cb) {
    var matches, substringRegex;

    // an array that will be populated with substring matches
    matches = [];

    // regex used to determine if a string contains the substring `q`
    substrRegex = new RegExp(q, 'i');

    // iterate through the pool of strings and for any string that
    // contains the substring `q`, add it to the `matches` array
    $.each(strs, function(i, str) {
      if (substrRegex.test(str)) {
        matches.push(str);
      }
    });

    cb(matches);
  };
};

 var states = ['Alabama ma ma ma', 'Alaska', 'Arizona', 'Arkansas', 'California',
   'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia', 'Hawaii',
   'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana',
   'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota',
   'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire',
   'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota',
   'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island',
   'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont',
   'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
 ];

$('#suggestionsearch #searchinput').typeahead({
  hint: true,
  highlight: true,
  minLength: 1
},
{
  name: 'states',
  source: substringMatcher(states)
});

jquery(not working):

...
...
$('#suggestionsearch #searchinput').typeahead({
      hint: true,
      highlight: true,
      minLength: 1
    },
    {
      name: 'states',
      source: substringMatcher('{!! URL::route('searchlive') !!}')
    });

My problem is to fetch the json results as array from the controller. I dont want statically array as example of states but a dynamic one as a result from my controller. How to define correctly the source? It says(not working jquery):

 `Uncaught TypeError: Cannot use 'in' operator to search for '27' in http://localhost:8000/search(…)`
Vasilis Greece
  • 861
  • 1
  • 18
  • 38
  • Did you try using `Bloodhound`. See [here](https://twitter.github.io/typeahead.js/examples/) and [here](http://stackoverflow.com/questions/21530063/how-do-we-set-remote-in-typeahead-js) – leo.fcx Dec 06 '16 at 18:42
  • Yes I am using typeahead.js but I cant find a solution for my problem – Vasilis Greece Dec 06 '16 at 18:47

0 Answers0