Guys, please help, I can not display the data from the request for autocomplete. I use this plugin: https://github.com/devbridge/jQuery-Autocomplete

The code is: $ (function () {

function Autocomplete(url, element){ element.autocomplete({ serviceUrl: url, onSelect: function (suggestion) { var thehtml = '<strong>Currency Name:</strong> ' + suggestion.name + ' <br> <strong>Symbol:</strong> ' + suggestion.id; $('#outputcontent').html(thehtml); } }); } $('.autocompleteSearch input.auto').keypress(function(){ Autocomplete($(this).attr('url'), $(this)); }); }); 

The problem is in the withdrawal of suggestion.name and suggestion.id

Returns the following JSON format from the server:

 suggestion: {id:[3], name:[Клиника коррекции зрения]} 

I did it like this, but I still did not pass:

 $(function () { $('#autocomplete-ajax').autocomplete({ source: function(request, response){ $.ajax({ type: 'POST', dataType: 'json', url : '/institution/GetList', data:{ maxRows: 12, // показать первые 12 результатов nameStartsWith: request.term // поисковая фраза }, success: function(data){ response($.map(data, function(item){ return { plink: item.plink, // ссылка на страницу товара label: item.title_ru // наименование товара } })); } }); }, select: function( event, ui ) { // по выбору - перейти на страницу товара // Вы можете делать вывод результата на экран location.href = ui.item.plink; return false; }, minLength: 3 // начинать поиск с трех символов }); }); 

Handler:

 public function GetList(){ $res = array(); if ($this->input->get('term')){ $result = $this->institutions_model->GetInstitutions(array('like' => $this->input->get('term'))); if (!empty($result)) { foreach ($result as $value) { $res[] = array('id' => $value->idMedicalFacilities, 'name' => $value->MedicalFacilitiesName); } } } echo json_encode($res); } 

Writes the following error in the console:

GET http://site.ru/user/null?query=%D0%BA 404 (Not Found)

  • Offtop. And how is it fundamentally better than the native plugin [Autocomplete jQuery UI] [1]? More documentation or hidden features? [1]: jqueryui.com/autocomplete - Deonis
  • Please give an example for Autocomplete jQuery UI so that you can get the Name of the record and Id of your choice from the list. Thank you - IOleg
  • This example doesn't work for me, that is, it doesn't alert and does not display anything on the page: $ (function () {function Autocomplete (url, element) {element.autocomplete ({minLength: 1, source: url, focus: function (event, ui) {// $ ("#project") .value (ui.item.label); return false;}, select: function (event, ui) {alert (ui.item.id); return false;}})} $ ('. autocompleteSearch input.auto'). keypress (function () {Autocomplete ($ (this) .attr ('url'), $ (this));});}); - IOleg
  • @Deonis, you must have enough karma to throw in the comment ... @junart if your "answer" does not give an answer, and you want to add a question - add to the question. - zb '

1 answer 1

The comment did not fit, therefore, write the answer

Please give an example

On the official site, examples of the sea. If that is not enough, I can show my own one, taken from a real project - a search by product group. (I removed the excess, I schematized server honor, my main settings are in $ .ajaxSetup () )

Js

 $('#search_field').autocomplete({ source: function(request, response){ $.ajax({ data:{ maxRows: 12, // показать первые 12 результатов nameStartsWith: request.term // поисковая фраза }, success: function(data){ response($.map(data, function(item){ return { plink: item.plink, // ссылка на страницу товара label: item.title_ru // наименование товара } })); } }); }, select: function( event, ui ) { // по выбору - перейти на страницу товара // Вы можете делать вывод результата на экран location.href = ui.item.plink; return false; }, minLength: 3 // начинать поиск с трех символов }); 

Php

 // Ищем в БД по ключевому слову $_POST['nameStartsWith'] // Если что-то находим, то формируем ответ: $response = array(); while($row = $res->fetch()){ $response[] = array( 'title_ru' => $row['title_ru'], 'plink' => itemPath($row['item_id']) // тут у меня функция формирует ссылку /* добавлять можно всё, что угодно. Хоть маму с папой впихнуть ;) */ ); } echo json_encode($response); exit; 

PS Options ajax off-screen - type: 'POST' , dataType: 'json' , url: '/ here is your /' , all sorts beforeSend, complete, error - at your discretion. All you have to do is connect the Autocomplete widget and specify your form search field selector.

  • Thank. Only now, when selecting the highlighted result, in the field inserts the record ID and not the name. On the contrary, the ID of the selected record is added to the hidden field, and the name of the selected element is added to input. - IOleg