Speed up a web service for auto complete and avoid too many method calls.
Posted
by jphenow
on Stack Overflow
See other posts from Stack Overflow
or by jphenow
Published on 2010-06-11T19:36:43Z
Indexed on
2010/06/11
19:52 UTC
Read the original article
Hit count: 223
So I've got my jquery autocomplete 'working,' but its a little fidgety since I call the webservice method each time a keydown() fires so I get lots of methods hanging and sometimes to get the "auto" to work I have to type it out and backspace a bit because i'm assuming it got its return value a little slow. I've limited the query results to 8 to mininmize time. Is there anything i can do to make this a little snappier? This thing seems near useless if I don't get it a little more responsive.
javascript
$("#clientAutoNames").keydown(function () {
$.ajax({
type: "POST",
url: "WebService.asmx/LoadData",
data: "{'input':" + JSON.stringify($("#clientAutoNames").val()) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
var serviceScript = data.d;
}
$("#autoNames").html(serviceScript);
$('#clientAutoNames').autocomplete({
minLength: 2,
source: autoNames,
delay: 100,
focus: function (event, ui) {
$('#project').val(ui.item.label);
return false;
},
select: function (event, ui) {
$('#clientAutoNames').val(ui.item.label);
$('#projectid').val(ui.item.value);
$('#project-description').html(ui.item.desc);
pkey = $('#project-id').val;
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "<br>" + item.desc + "</a>")
.appendTo(ul);
}
}
});
});
WebService.asmx
<WebMethod()> _
Public Function LoadData(ByVal input As String) As String
Dim result As String = "<script>var autoNames = ["
Dim sqlOut As Data.SqlClient.SqlDataReader
Dim connstring As String = *Datasource*
Dim strSql As String = "SELECT TOP 2 * FROM v_Clients WHERE (SearchName Like '" + input + "%') ORDER BY SearchName"
Dim cnn As Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection(connstring)
Dim cmd As Data.SqlClient.SqlCommand = New Data.SqlClient.SqlCommand(strSql, cnn)
cnn.Open()
sqlOut = cmd.ExecuteReader()
Dim c As Integer = 0
While sqlOut.Read()
result = result + "{"
result = result + "value: '" + sqlOut("ContactID").ToString() + "',"
result = result + "label: '" + sqlOut("SearchName").ToString() + "',"
'result = result + "desc: '" + title + " from " + company + "',"
result = result + "},"
End While
result = result + "];</script>"
sqlOut.Close()
cnn.Close()
Return result
End Function
I'm sure I'm just going about this slightly wrong or not doing a better balance of calls or something.
Greatly appreciated!
© Stack Overflow or respective owner