Menu ▼

Posted By :
Total Views : 8227

JQuery ajax autocomplete extender textbox using json response type

This example shows you how to implement autocomplete functionality for textbox by using jquery, jqueryui, jquery ajax and json response from the server.



Add reference to the jquery ui css, jquery and jquery ui.

<link href="" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>

Bind autocomplete functionality to textbox in document.ready event.

<script language="javascript">
    $(document).ready(function () {
        $("#<% =txtCountry.ClientID%>").autocomplete({
            source: function (request, response) {
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "default.aspx/LoadCountry",
                    data: "{input:'" + request.term + "'}",
                    dataType: "json",
                    success: function (output) {
                    error: function (errormsg) {

in the above code url we have mentioned as "default.aspx/LoadCountry" where default.aspx is page name and LoadCountry is the web method name which returns the JSON result set.

Data we have given as -> data: "{input:'" + request.term + "'}". Where input is the parameter name in the C# web method. and request.term will pass the value we entered in the textbox.

And if the ajax method successfully executed then it will call the success method if any error is there then error method will be raised in the above code.

Now write the C# web method

Add name space -> using System.Web.Services;

public static List<string> LoadCountry(string input)
    //Get the countries list from database, for this example I am creating sample output
    //return GetCountriesfromDB(input);

    return GetCountries().FindAll(item => item.ToLower().Contains(input.ToLower()));


public static List<string> GetCountries()
        List<string> CountryInformation = new List<string>();
        CountryInformation.Add("United States");
        CountryInformation.Add("United Kingdom");
        CountryInformation.Add("South Korea");
        CountryInformation.Add("New Zealand");
        return CountryInformation;

To declare web method LoadCountry, we have to specify the access specifier as public and static. and add [WebMethod] attribute.In the above code GetCountries() method used to prepare the sample data, you can replace this with the original data.

Now execute the solution to get the output as shown in the above image....

you can download the source code form here... Download