Jquery Autocomplete With Database
Solution 1:
that is not how jQuery Autocomplete works,
jQuery autocomplete automatically sends the text entered in the text box to the location you specify in a querystring "term" you access it in webmethod or handler like this
stringinput = HttpContext.Current.Request.QueryString["term"];
something like this
[WebMethod]
publicstatic List<string> GetAutoCompleteData(string Car)
{
string input = HttpContext.Current.Request.QueryString["term"];
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["CarsConnectionString"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ @SearchText +'%", con))
{
con.Open();
cmd.Parameters.AddWithValue("@SearchText", input);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["Car"].ToString());
}
return result;
}
}
}
this goes in your .aspx page
$(".ui-autocomplete").autocomplete({
source: "Admin_home.aspx/GetAutoCompleteData",
select: function (event, ui) { }
});
EDIT:
I've never actually done this in web method , I usually use a handler .ashx , but this should work just as good.
when you have all that changed , then run the site in debug mode, start to type in the textbox and fit f12 and watch the traffic that this is causing - if you type "abc" it should look like
Admin_home.aspx/GetAutoCompleteData?term=abc
then the response you might have to play with a little , by default .net is going to add "d : ...." to the response to client side , but you can watch it and adjust accordinly
Another Edit:
<asp:Textbox ID="query"class="ui.autocomplete">
is not what you put in the jquery
$(".ui-autocomplete").autocomplete({
it should be
<asp:Textbox ID="query"class="ui-autocomplete">
Yet, Another Edit:
This is missing a single quote
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ @SearchText +'%", con))
replace with
using (SqlCommand cmd = new SqlCommand("select DISTINCT Car from T_Car where Car like '%'+ @SearchText +'%' ", con))
Solution 2:
try this maybe it would help
<scripttype="text/javascript">
$(function() {
$(".ui-autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
url: "Admin_home.aspx/GetAutoCompleteData",
data: "{ 'Car': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
Post a Comment for "Jquery Autocomplete With Database"