user1327064 user1327064 - 1 month ago 7
ASP.NET (C#) Question

Autocomplete jquery plugin does not work when data comes from database?

I am using this plugin for textarea suggestion (auto completion). It is working fine as long as list is hardcoded. like this :-


var suggests = ["Action", "ActionScript", "Borland"];


But I need words list from the database. When i get list from database, plugin does not respond. Here is what I am doing:-

Plugin I am using:-


https://github.com/imankulov/asuggest/


Jquery:-

$(document).ready(function() {
var suggests = getList();
var $txt = $('#<%=txtArea.ClientID %>');
$txt.asuggest(suggests);
});

function getList() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajaxService.asmx/autocompletelist",
data: "{groupUid:'" + 4 + "', clientUid: '" + 8 + "'}",
dataType: "json",
success: function(data) {
return (data.d);
},
error: function(result) {
alert("No Match");
}
});
}


code behind:-

[WebMethod]
public List<string> autocompletelist(int groupUid, int clientUid)
{
//call to database for the list.
//code/

List<string> result = new List<string>();
result.Add("Action");
result.Add("ActionScript");
result.Add("Borland");
return result;
}


Please suggest? Is it something to do with square brackets? How to get that in return from database?

Answer

An ajax success function is executed asynchronously (it doesn't get fired until a response is received), but you're trying to use its result in a synchronous fashion. So when you call $txt.asuggest(suggests);, nothing happens because suggests has not been populated yet. This is because the ajax request hasn't finished, but your code doesn't know that. The simplest way to fix this is to put the logic for the UI in the success method itself. That way your plugin wont be called until the suggests variable is guaranteed to be populated. Try this:

$(document).ready(function() {
    getList();
});

function getList() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "ajaxService.asmx/autocompletelist",
        data: "{groupUid:'" + 4 + "', clientUid: '" + 8 + "'}",
        dataType: "json",
        success: function(data) {
            var $txt = $('#<%=txtArea.ClientID %>');
            $txt.asuggest(data);
        },
        error: function(result) {
            alert("No Match");
        }
    });
}
Comments