How to use source: function()... and AJAX in JQuery UI autocomplete

258,443

Solution 1

Inside your AJAX callback you need to call the response function; passing the array that contains items to display.

jQuery("input.suggest-user").autocomplete({
    source: function (request, response) {
        jQuery.get("usernames.action", {
            query: request.term
        }, function (data) {
            // assuming data is a JavaScript array such as
            // ["[email protected]", "[email protected]","[email protected]"]
            // and not a string
            response(data);
        });
    },
    minLength: 3
});

If the response JSON does not match the formats accepted by jQuery UI autocomplete then you must transform the result inside the AJAX callback before passing it to the response callback. See this question and the accepted answer.

Solution 2

Try this code. You can use $.get instead of $.ajax

$( "input.suggest-user" ).autocomplete({
    source: function( request, response ) {
        $.ajax({
            dataType: "json",
            type : 'Get',
            url: 'yourURL',
            success: function(data) {
                $('input.suggest-user').removeClass('ui-autocomplete-loading');  
                // hide loading image

                response( $.map( data, function(item) {
                    // your operation on data
                }));
            },
            error: function(data) {
                $('input.suggest-user').removeClass('ui-autocomplete-loading');  
            }
        });
    },
    minLength: 3,
    open: function() {},
    close: function() {},
    focus: function(event,ui) {},
    select: function(event, ui) {}
});

Solution 3

$("#id").autocomplete(
{
    search: function () {},
    source: function (request, response)
    {
        $.ajax(
        {
            url: ,
            dataType: "json",
            data:
            {
                term: request.term,
            },
            success: function (data)
            {
                response(data);
            }
        });
    },
    minLength: 2,
    select: function (event, ui)
    {
        var test = ui.item ? ui.item.id : 0;
        if (test > 0)
        {
           alert(test);
        }
    }
});

Solution 4

On the .ASPX page:

  <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <html xmlns="http://www.w3.org/1999/xhtml">
  <head id="Head1" runat="server">
        <title>AutoComplete Box with jQuery</title>
        <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>  
        <script type="text/javascript">
            $(document).ready(function() {
                SearchText();
            });
            function SearchText() {
                $(".autosuggest").autocomplete({
                    source: function(request, response) {
                        $.ajax({
                            type: "POST",
                            contentType: "application/json; charset=utf-8",
                            url: "Default.aspx/GetAutoCompleteData",
                            data: "{'username':'" + document.getElementById('txtSearch').value + "'}",
                            dataType: "json",
                            success: function (data) {
                                if (data != null) {

                                    response(data.d);
                                }
                            },
                            error: function(result) {
                                alert("Error");
                            }
                        });
                    }
                });
            }
        </script>
  </head>
  <body>
      <form id="form1" runat="server">
          <div class="demo">
           <div class="ui-widget">
            <label for="tbAuto">Enter UserName: </label>
       <input type="text" id="txtSearch" class="autosuggest" />
    </div>
        </form>
    </body>
    </html>    

In your .ASPX.CS code-behind file:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod]
    public static List<string> GetAutoCompleteData(string username)
    {
        List<string> result = new List<string>();
            SqlConnection con = new SqlConnection("Data Source=YourDatasource;Initial Catalog=DatabseName;uid=sa;password=123");

            SqlCommand cmd = new SqlCommand("select DISTINCT Name from Address where Name LIKE '%'+@Name+'%'", con);
            con.Open();
                cmd.Parameters.AddWithValue("@Name", username);
                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    result.Add(dr["Name"].ToString());
                }
                return result;
        }
}

Solution 5

This is completely new working code with sample AJAX call.

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css" rel="stylesheet" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>

<div>
    <div id="project-label">Select a project (type "j" for a start):</div>
    <img id="project-icon" src="images/transparent_1x1.png" class="ui-state-default" alt="" />
    <input id="project" />
    <input type="hidden" id="project-i" />
</div>


@*Auto Complete*@
<script>
    $(function () {

        $("#project").autocomplete({
            minLength: 0,
            source : function( request, response ) {
                $.ajax({
                    url: "http://jsonplaceholder.typicode.com/posts/1/comments",
                    dataType: "jsonp",
                    data: {
                        q: request.term
                    },
                    success: function (data) {
                        response( data );
                    }
                });
            },
            focus: function (event, ui) {
                $("#project").val(ui.item.label);
                return false;
            },
            select: function (event, ui) {
                $("#project").val(ui.item.name);
                $("#project-id").val(ui.item.email);                    

                return false;
            }
        })
            .data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                    .data("ui-autocomplete-item", item)
                    .append("<a> " + item.name + "<br>" + item.email + "</a>")
                    .appendTo(ul);
            };
    });
</script>
Share:
258,443

Related videos on Youtube

Bernie
Author by

Bernie

I'm Bernhard from Frankfurt. Java EE developer.

Updated on July 05, 2022

Comments

  • Bernie
    Bernie almost 2 years

    I need a little bit help with JQuery UI Autocomplete. I want my textfield (.suggest-user) display names from an AJAX request. This is what I have:

    jQuery("input.suggest-user").autocomplete({
        source : function(request, response) {
            var name = jQuery("input.suggest-user").val();
            jQuery.get("usernames.action?query=" + name, function(data) {
                console.log(data);  // Ok, I get the data. Data looks like that:
                test = data;        // ["[email protected]", "[email protected]","[email protected]"]
                return test;        // But what now? How do I display my data?
            });
        },
        minLength : 3
    });
    

    Any help is very much appreciated.

  • Eli
    Eli almost 10 years
    It is a little bit more simple. jQuery autocomplete supports a get url for the 'source' parameter. source: "usernames.action" . Your method should return a json array and should accept a parameter called "term".
  • Salman A
    Salman A almost 10 years
    @Elisa: correct. The OP used a callback in the example (may be for a reason) so I followed suit.
  • geoidesic
    geoidesic over 9 years
    This doesn't work for me... it returns all of the items in the list, instead of the ones that match the query term.
  • Salman A
    Salman A over 9 years
    OP filters the results on server side, this answer assumes that.
  • Tim Truston
    Tim Truston about 9 years
    Is there a way to filter results in the front end, with the jquery autocomplete library, after doing an ajax call?
  • Salman A
    Salman A about 9 years
    @TechyTimo you can filter the results inside jQuery.get callback before calling the response function. In the above example the code would go where the comments are.
  • NickG
    NickG over 8 years
    @Jaikrat Because a GET request causes: "An attempt was made to call the method 'GetAutoCompleteData' using a GET request, which is not allowed." See: stackoverflow.com/questions/18703838/…
  • Jaikrat
    Jaikrat over 8 years
    Hello @SalmanA, can you check this once pls stackoverflow.com/questions/33410824/… Thanks.
  • SagittariusA
    SagittariusA about 8 years
    response() function inside ajax call will create some <li> elements to display. How shall I do if I want to add an attribute to that <li> when it's created?
  • Salman A
    Salman A about 8 years
    @LoryLory if you want to modify the autocomplete's suggestion list then search stackoverflow for "jquery ui autocomplete _renderItem".
  • Sasa1234
    Sasa1234 over 6 years
    What does "query: request.term" means?
  • Sasa1234
    Sasa1234 over 6 years
    @Bernie What does "query: request.term" means?
  • Ross
    Ross over 6 years
    @Sasa1234 - "query: request.term" is what is send to the server as a query string. In this example if user enters FOO then request.term=foo and server request will be send to usernames.action?query=foo.
  • Miro Lehtonen
    Miro Lehtonen over 4 years
    I see you get a jsonp response from the ajax call. What is the name of the callback function?