Jquery AutoComplete with database

I cannot seem to figure out what is wrong with the code for the autocomplete search bar.

The only thing I can think of is that I referenced the wrong thing under URL

aspx Javascript

    $(document).ready(function() {
        SearchText();
    });
    function SearchText() {
        $(".ui-autocomplete").autocomplete({
            source: function(request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "Admin_home.aspx/GetAutoCompleteData",
                    data: "{'Car':'" + document.getElementById('query').value + "'}",
                    dataType: "json",
                    success: function(data) {
                        response(data.d);
                    },
                    Error: function(results) {
                        alert("Error");
                    }
                });
            }
        });
    }

</script>`

aspx html code

I cant seem to type or paste the html here. It is just a
asp:Textbox ID=”query” class=”ui.autocomplete”

c# code

    [WebMethod]
    public static List<string> GetAutoCompleteData(string Car)
    {
        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", Car);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    result.Add(dr["Car"].ToString());
                }
                return result;
            }
        }
    }

Would part of the html need to be wrapped in an AJAX update panel?

Also, I am having the search pull names from sql server 2005.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

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

         string input = HttpContext.Current.Request.QueryString["term"];

something like this

              [WebMethod]
public static 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

<script type="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>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply