Materialize ajax autocomplete

I use the materialize autocomplete plugin to create multiple autocomplete tags. The plugin works fine, but only with data transferred in the form of an array defined in advance. If data is transferred from an ajax call, the plugin does not display a drop-down menu with parameters, as if there were no results. In fact, there are results, they are cached (using the cache option) and displayed as a drop-down list only after re-printing the search phrase.

To summarize, the autocomplete plugin does not wait for ajax to fulfill its request and deliver the data, so the drop-down menu is not displayed at first. Is there a way to get this plugin to display offers in a drop-down list as soon as they are received through an ajax call?

Plugin initialization:

autocomplete = $('#multipleInput').materialize_autocomplete({ cacheable: true, throttling: true, multiple: { enable: true, maxSize : 5 }, appender: { el: '.ac-users' }, dropdown: { el: '#multipleDropdown' }, getData: function (value, callback) { callback(value,getAjaxDropdowValuesAutocomplete(value)); } }); 

Function for getting values ​​from the database:

 function getAjaxDropdowValuesAutocomplete(value){ var returnArray = [], dataArray, innerObject = {}, postParamsObj = {"search" : value}; $.ajax({ type: "POST", url: '/search-elements', data: postParamsObj, success: function( msg ) { dataArray = msg['data']; for(var i = 0;i < dataArray.length; i++){ innerObject = {}; innerObject["id"] = dataArray[i][0]; innerObject["text"] = dataArray[i][1] + " " + dataArray[i][2]; returnArray.push(innerObject); } // returnArray format [{ 'id': '1', 'text': 'Johnny Bravo' }] }, error : function(msg){ } }); return returnArray; } 
+5
source share
1 answer

You can try to initialize autocomplete during the ajax request success callback, and not vice versa. This way, you are sure to get the data before trying to start binding autocomplete events. eg.

 function getAjaxDropdowValuesAutocomplete(value) { var returnArray = [], dataArray, innerObject = {}, postParamsObj = {"search": value}; $.ajax({ type: "POST", url: '/search-elements', data: postParamsObj, success: function (msg) { dataArray = msg['data']; for (var i = 0; i < dataArray.length; i++) { innerObject = {}; innerObject["id"] = dataArray[i][0]; innerObject["text"] = dataArray[i][1] + " " + dataArray[i][2]; returnArray.push(innerObject); } // returnArray format [{ 'id': '1', 'text': 'Johnny Bravo' }] autocomplete = $('#multipleInput').materialize_autocomplete({ cacheable: true, throttling: true, multiple: { enable: true, maxSize: 5 }, appender: { el: '.ac-users' }, dropdown: { el: '#multipleDropdown' }, getData: returnArray }); }, error: function (msg) { } }); return returnArray; } 
0
source

Source: https://habr.com/ru/post/1273257/


All Articles